變量,判斷,重複動作:
位置參數:
$# 傳遞到shell腳本的參數個數. 一般與shift聯合使用,實作參數的逐個處理。
$* ,$@ 在沒有外加雙引号的情況下,兩者一樣,都為列舉shell的所有參數。并傳遞給程式。
"$*" 将所有參數視作單個字元。
"$@"将所有參數作為單個個體,并保留參數的内嵌空格。
特殊變量:
POSIX的内置shell變量:
# 目前參數個數
@ 傳遞給目前指令的指令參數,在雙引号内,會展開給别參數,并保留白格。
* 目前程序的參數。在雙引号内,則将參數作為單一字元。
- 在引用時給與shell的選項。
? 前一個指令的退出狀态。
$ shell程序的程序編号。processID
0 shell程式名稱。
! 最近一個背景指令的processID
PATH 指令查找路徑。
PS1 主要的指令提示符 普通使用者為$ root使用者為# (預設)
PS2 行繼續的提示符 >
LC_COLLATE 用來排序目前的local名稱。
參數展開:
替換運算符:
<1>${varname : -word} varname非空,則為varname 若空 則為word, word為預設值。
<2>${varname:=word} varname存在且不是null 則傳回varname值,否則,則設定word,并傳回其值。
<3>${varname:?message}varname存在且非空,傳回其值,否則,顯示varname:message并退出目前腳本,省略message則會出現預設資訊:parameter null or not set
<4>${varname:+word}varname存在且非空。傳回word 否則傳回null
模式比對運算符:
${variable#pattern}比對pattern在variable裡的最短部分 去除并傳回剩餘部分。
${variable##pattern}比對pattern在variable裡的最長部分 去除并傳回剩餘部分。
${variable%pattern}從結尾開始,比對pattern在variable裡的最短部分 去除并傳回剩餘部分
${variable%%pattern}從結尾開始,比對pattern在variable裡的最長部分 去除并傳回剩餘部分
Examples. path=/home/alleria/men/log.file.name
運算符 結果
${path#/*/} alleria/men/log.file.name
${path##/*/} log.file.name
${path%.*} /home/alleria/men/log.file
${path%%.*} /home/alleria/men/log
test指令:
用法:
test [ -f file ]
[ -f file ]
if [ -f file ] && [ -n file1 ]
[ -f file -o -n file1 ] -o 為 邏輯 or -a 為邏輯and
測試否定 可加! 如 [ ! -f file ]
所有的參數展開都需要用引号括起來,如 if [ -f "$file" ]
字元串的比較時,通常在各個字元串的前面添加一個字母,如x 例如: if [ "x$file" = "x$file1" ] 以此來避免字元串的開始為-,将字元串誤判為參數的情況發生
test 的數字比較隻用于整數,浮點數不可。
選項:
-b file file是裝置檔案
-c file file是字元檔案
-d file file是目錄
-e file file存在
-f file file是一般檔案
-g file file有設定setgid位
-u file file有設定setuid
-h file file是一符号連接配接
-L file file是符号連接配接 等同-h
-n string string是非null
-p file file是一個命名的管道
-r file file是可讀的
-w file file是可寫入的
-S file file是socket
-s file file不是空的
-t n 檔案描述符n指向一終端
-x file file可執行或者可查找路徑
-z string string為null
s1 = s2 兩字元串相同
s1 != s2 兩字元串不同
n1 -eq n2 兩整數相等
n1 -ne n2 兩整數不等
n1 -lt n2 n1 小于 n2
n1 -gt n2 n1 大于 n2
n1 -le n2 n1 小于或等于n2
n1 -ge n2 n1 大于或等于n2
範例:
if [ -f "$file" ]
echo $file is a regular file
elif [ -d "$file" ]
echo $file is a directory
fi
if [ -x "$file" ]
echo $file is not executable
if-elif-else-fi
if pipeline
[pipeline]
then
if-statements-true
elif
statemens-elif-true
else
statmens-others-fails
case語句:
case $1 in
-f)
....
;;
-d | --directory )
*)
exit 1
esac
for 語句:
for statement
do
statement-true
done
在statement-true處可使用while ease 語句
##################################################################################################
shell 在編寫過程中的錯誤:1.在參數設定部分 将` ......` 寫成了‘ ......’ (單引号)
error_code: line 45 : test : integer expression expected
2.在參數測驗 null errorcode : unary operater expended
3. shift SPELLING WRONG。