Shell 語法
變量
name='John' #or declare name='Docn' 定義局部變量
export NAME='Don' #定義全局變量
echo "$name""$NAME" #雙引號內 $ 引用名稱對應內容
輸入
read commit #從命令行讀取一行內容
echo "$commit"
條件測試
test
expr
測試文件狀態
syntax
test condition
或 [ condition ]
方括號形式使用需注意括號與條件間需要留有空格
測試參數 | 解釋 | 測試參數 | 解釋 |
---|---|---|---|
-d | 目錄 | -s | 文件長度大於0、非空 |
-f | 正規文件 | -w | 可寫 |
-r | 文件可讀 | -x | 可執行 |
usage
$ ls -l syntax.md
-rw-r--r-- 1 xugang staff 597 2 13 23:28 syntax.md
$ test -f syntax.md # 也可寫成 [ -f syntax.md ]
$ echo $?
0
測試時使用邏輯操作符
-a
邏輯與-o
邏輯或!
邏輯否
usage
$ ll 1.1.sh syntax.md
-rwxr-xr-x 1 xugang staff 239B 2 4 14:58 1.1.sh
-rw-r--r-- 1 xugang staff 818B 2 13 23:33 syntax.md
$ [ -x 1.1.sh -o -x syntax.md ]
$ echo $?
0
字符串測試
syntax
- test "string"
- test string_operator "string"
- test "string" string_operator "string"
- [ string_operator string ]
- [ string string_operator string ]
數值測試
expr用法
數組
索引數組
#數組定義, 元素以空格分隔,注意等號前後不能有空格
array=( one two three )
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
limits=( 10 20 30 40 )
#打印數組
printf "%s\n" "${array[@]}"
printf "%s\n" "${files[@]}"
printf "%s\n" "${limits[@]}"
#循環遍歷數組
for i in "${array[@]}" ; do
echo $i
# do whatever on $i
done
關聯數組
// 申明關聯數組
declare -A ass_array1
// 數組名[索引] = 變量
ass_array1[index1] = val