CONDITION:
bash指令:
用指令的執行狀态結果;
成功:true
失敗:flase
成功或失敗的意義:取決于用到的指令;
單分支:
if CONDITION; then
if-true
fi
雙分支:
else
if-false
多分支:
if CONDITION1; then
elif CONDITION2; then
if-ture
elif CONDITION3; then
...
esle
all-false
逐條件進行判斷,第一次遇為“真”條件時,執行其分支,而後結束;
示例:使用者鍵入檔案路徑,腳本來判斷檔案類型;
#!/bin/bash
#
read -p "Enter a file path: " filename
if [ -z "$filename" ]; then
echo "Usage: Enter a file path."
exit 2
if [ ! -e $filename ]; then
echo "No such file."
exit 3
if [ -f $filename ]; then
echo "A common file."
elif [ -d $filename ]; then
echo "A directory."
elif [ -L $filename ]; then
echo "A symbolic file."
echo "Other type."
fi
注意:if語句可嵌套;
循環:for, while, until
循環體:要執行的代碼;可能要執行n遍;
進入條件:
退出條件:
for循環:
for 變量名 in 清單; do
循環體
done
執行機制:
依次将清單中的元素指派給“變量名”; 每次指派後即執行一次循環體; 直到清單中的元素耗盡,循環結束;
示例:添加10個使用者, user1-user10;密碼同使用者名;
#!/bin/bash
#
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
清單生成方式:
(1) 直接給出清單;
(2) 整數清單:
(a) {start..end}
(b) $(seq [start [step]] end)
(3) 傳回清單的指令;
$(COMMAND)
(4) glob