目錄
簡介
除了基本的獲取腳本執行時的傳入參數外, 還有更便捷的語法糖: 參數默認值, 自動賦值.
基本傳參
先來一個示例:
#!/bin/sh
echo 參數0: $0;
echo 參數1: $1;
echo 參數2: $2;
echo 參數3: $3;
echo 參數4: $4;
執行測試腳本
[root@yjx214 tmp]# sh testParam.sh a b c d
所有參數: a b c d
參數0: testParam.sh
參數1: a
參數2: b
參數3: c
參數4: d
| 參數處理 | 說明 |
|---|---|
| $# | 傳遞到腳本的參數個數 |
| $* | 以一個單字符串顯示所有向腳本傳遞的參數。 如"$*"用「"」括起來的情況、以"$1 $2 … $n"的形式輸出所有參數。 |
| $$ | 腳本運行的當前進程ID號 |
| $! | 后台運行的最后一個進程的ID號 |
| $@ | 與$*相同,但是使用時加引號,並在引號中返回每個參數。 如"$@"用「"」括起來的情況、以"$1" "$2" … "$n" 的形式輸出所有參數。 |
| $- | 顯示Shell使用的當前選項,與set命令功能相同。 |
| $? | 顯示最后命令的退出狀態。0表示沒有錯誤,其他任何值表明有錯誤。 |
$* 與 $@ 區別
$* 與 $@ 區別:
- 相同點:都是引用所有參數。
- 不同點:只有在雙引號中體現出來。假設在腳本運行時寫了三個參數 1、2、3,,則 " * " 等價於 "1 2 3"(傳遞了一個參數),而 "@" 等價於 "1" "2" "3"(傳遞了三個參數)。
#!/bin/bash
# author:菜鳥教程
# url:www.runoob.com
echo "-- \$* 演示 ---"
for i in "$*"; do
echo $i
done
echo "-- \$@ 演示 ---"
for i in "$@"; do
echo $i
done
執行腳本,輸出結果如下所示:
$ chmod +x test.sh
$ ./test.sh 1 2 3
-- $* 演示 ---
1 2 3
-- $@ 演示 ---
1
2
3
默認參數(變量默認值)
if 繁瑣方式
if [ ! $1 ]; then
$1='default'
fi
- 變量為null
取默認值
- 變量 為 null
${vari-defaultValue}
實踐
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name}
[root@yjx214 /]# echo ${name-yjx}
yjx
[root@yjx214 /]# name=
[root@yjx214 /]# echo ${name-yjx}
[root@yjx214 /]# echo ${name}
[root@yjx214 /]#
= 變量為null時, 同時改變變量值
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name=yjx}
yjx
[root@yjx214 /]# echo $name
yjx
[root@yjx214 /]# name=""
[root@yjx214 /]# echo ${name=yjx}
[root@yjx214 /]#
:- 變量為null 或 空字符串
取默認值
- 變量為null
- 變量為空字符串
${vari:-defaultValue}
:= 變量為null 或 空字符串, 同時改變變量值
{$vari:=defaultValue}
測試 null
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name:=yjx}
yjx
[root@yjx214 /]# echo ${name}
yjx
[root@yjx214 /]#
測試 空字符串
[root@yjx214 /]# name=""
[root@yjx214 /]# echo ${name:=yjx}
yjx
[root@yjx214 /]# echo $name
yjx
:? 變量為null 或 空字符串時報錯並退出
[root@yjx214 /]# unset name
[root@yjx214 /]# echo ${name:?yjx}
-bash: name: yjx
[root@yjx214 /]# name=""
[root@yjx214 /]# echo ${name:?yjx}
-bash: name: yjx
[root@yjx214 /]# name="guest"
[root@yjx214 /]# echo ${name:?yjx}
guest
:+ 變量不為空時使用默認值
與 :- 相反
[root@yjx214 /]# name="guest"
[root@yjx214 /]# echo ${name:+yjx}
yjx
[root@yjx214 /]# echo $name
guest
