Title here
Summary here
如果 command
嘅退出碼係 0
,咁就執行 then
嘅內容。
if command
then
...
fi
另一種格式。
if command; then
...
fi
if command; then
...
else
...
fi
if command; then
...
elif command; then
...
fi
檢查 soda 用戶係咪存在。
#!/usr/bin/env bash
if grep soda /etc/passwd
then
echo "soda exists"
fi
soda:x:1001:1001:,,,:/home/soda:/bin/bash
soda exists
grep
有數據嗰陣,退出碼係 0
,冇數據嗰陣退出碼係 1
。
測試條件,如果係真,返回碼係 0
,否則返回碼係 1
。
test - check file types and compare values
基本語法。
test EXPRESSION
簡短語法。
[ EXPRESSION ]
喺命令行執行完之後,可以用 echo $?
睇返嘅返回碼。
[ -e file ]
:文件係咪存在。[ -d file ]
:係咪存在同埋係目錄。[ -f file ]
:係咪存在同埋係文件。[ -s file ]
:係咪存在同埋唔係空嘅。[ -r file ]
:係咪存在同埋可讀。[ -w file ]
:係咪存在同埋可寫。[ -x file ]
:係咪存在同埋可執行。[ -O file ]
:係咪存在同埋屬於現時嘅用戶。[ -G file ]
:係咪存在同埋屬於用戶組。[ a -nt b ]
:文件 a 係咪比 b 新。[ a -ot b ]
:文件 a 係咪比 b 舊。如果 file
或者 $file
變數包含空格,要用雙引號。
[ -e "file" ]
[ -e "$file" ]
[ -z str ]
:字串係咪空(長度為 0)。[ -n str ]
:字串係咪唔空(長度唔為 0)。[ s1 = s2 ]
:字串係咪相等。[ s1 != s2 ]
:字串係咪唔等。[ a -eq b ]
:兩個數係咪相等。[ a -ne b ]
:兩個數係咪唔等。[ a -gt b ]
:a 係咪大過 b。[ a -ge b ]
:a 係咪大過或等於 b。[ a -lt b ]
:a 係咪細過 b。[ a -le b ]
:a 係咪細過或等於 b。同傳統嘅編程語言一致。
[ cond1 ] && [ cond2 ]
[ cond1 ] || [ cond2 ]
雙括號可以使用高級數學表達式,無需轉義。
if (( 2**10 > 1000 ))
then
...
fi
提供字串嘅高級匹配模式。
if [[ $BASH_VERSION == 5.* ]]
then
...
fi
#!/usr/bin/env bash
# Script 嘅第一個參數
case "$1" in
start)
echo "Starting the service..."
# 喺呢度加入啟動服務嘅指令
;;
stop)
echo "Stopping the service..."
# 喺呢度加入停止服務嘅指令
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
;;
esac
$0
:腳本名稱。$1
:腳本嘅第一個參數)
:分支條件結束標記。;;
:分支命令結束標記。*)
:默認分支,所有分支唔匹配時執行。