1. 单分支
格式:
语句
fi
如下,检测是否存在mysql 用户,存在则打印 mysql exist
#!/bin/bash
if id mysql; then
echo "mysql exist."
fi
2. 双分支
格式:
语句
else
语句
fi
如下,如果存在指定用户,则显示已经存在,并显示其ID号,否则就添加该用户,并显示其ID:
username=mysql
if id$username &>/dev/null; then
Id=`grep "^$username\>" /etc/passwd | cut -d: -f3`
Shell=`grep "^$username\>" /etc/passwd | cut -d: -f7`
echo "$username exist, ID is $Id, shell is $Shell."
else
useradd $username
Id=`grep "^$username\>" /etc/passwd | cut -d: -f3`
echo "$username ID is $Id."
fi
3. 嵌套if语句
格式:
if [条件2]; then
语句
else
语句
fi
else
语句
fi