咱們能夠在執行 Shell 腳本時,向腳本傳遞參數,腳本內獲取參數的格式爲:$n。n 表明一個數字,1 爲執行腳本的第一個參數,2 爲執行腳本的第二個參數,以此類推……shell
如下實例咱們向腳本傳遞三個參數,並分別輸出,其中 $0 爲執行的文件名:bash
#!/bin/bash # author:hong echo "current file name is $0" echo "first param name is $1" echo "first param name is $2" echo "first param name is $3"
爲腳本設置可執行權限,並執行腳本,輸出結果以下所示:spa
[root@localhost shelltest]# chmod +x test.sh [root@localhost shelltest]# ./test.sh p1 p2 p3 ./test.sh: line 1: uthor:hong: command not found current file name is ./test.sh first param name is p1 first param name is p2 first param name is p3
參數處理 | 說明 |
---|---|
$# | 傳遞到腳本的參數個數 |
$* | 以一個單字符串顯示全部向腳本傳遞的參數。 如"$*"用「"」括起來的狀況、以"$1 $2 … $n"的形式輸出全部參數。 |
$$ | 腳本運行的當前進程ID號 |
$! | 後臺運行的最後一個進程的ID號 |
$@ | 與$*相同,可是使用時加引號,並在引號中返回每一個參數。 如"$@"用「"」括起來的狀況、以"$1" "$2" … "$n" 的形式輸出全部參數。 |
$- | 顯示Shell使用的當前選項,與set命令功能相同。 |
$? | 顯示最後命令的退出狀態。0表示沒有錯誤,其餘任何值代表有錯誤。 |
#!/bin/bash
# author:hong # echo "current file name is $0" # echo "first param name is $1" # echo "first param name is $2" # echo "first param name is $3" echo "all the param num is $#" echo "all the param print by a string is $*" echo "running process id num is $$" echo "last id num is $!" echo "all the param print by quotation marks is $@" echo "show the shell opition: $-" echo "show the last commond exit state: $?"
執行腳本結果code
[root@localhost shelltest]# ./test.sh p1 p2 p3 all the param num is 3 all the param print by a string is p1 p2 p3 running process id num is 11842 last id num is all the param print by quotation marks is p1 p2 p3 show the shell opition: hB show the last commond exit state: 0
示例blog
#!/bin/bash # author:hong echo "-- \$* 演示 ---" for i in "$*"; do echo $i done echo "-- \$@ 演示 ---" for i in "$@"; do echo $i done
結果進程
[root@localhost shelltest]# chmod +x test1.sh [root@localhost shelltest]# ./test1.sh p11 p22 p33 -- $* 演示 --- p11 p22 p33 -- $@ 演示 --- p11 p22 p33