多分支:
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
...
esle
all-false
fi
逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束;
示例:用户键入文件路径,脚本来判断文件类型;
#!/bin/bash
#
read -p "Enter a file path: " filename
if [ -z "$filename" ]; then
echo "Usage: Enter a file path."
exit 2
fi
if [ ! -e $filename ]; then
echo "No such file."
exit 3
fi
if [ -f $filename ]; then
echo "A common file."
elif [ -d $filename ]; then
echo "A directory."
elif [ -L $filename ]; then
echo "A symbolic file."
else
echo "Other type."
fi
注意:if语句可嵌套;
循环:for, while, until
循环体:要执行的代码;可能要执行n遍;
进入条件:
退出条件:
if [ ! $UID -eq 0 ]; then
echo "Only root."
exit 1
fi
for i in {1..10}; do
if id user$i &> /dev/null; then
echo "user$i exists."
else
useradd user$i
if [ $? -eq 0 ]; then
echo "user$i" | passwd --stdin user$i &> /dev/null
echo "Add user$i finished."
fi
fi
done
for file in $(ls /var); do
if [ -f /var/$file ]; then
echo "Common file."
elif [ -L /var/$file ]; then
echo "Symbolic file."
elif [ -d /var/$file ]; then
echo "Directory."
else
echo "Other type."
fi
done
for state in $( netstat -tan | grep "^tcp\>" | awk '{print $NF}'); do
if [ "$state" == 'ESTABLISHED' ]; then
let estab++
elif [ "$state" == 'LISTEN' ]; then
let listen++
else
let other++
fi
done