天天看點

Shell腳本中$#,$@,$0,$1,$2等變量的含義

在看腳本的時候經常可以看到$#,$@,$0,$1,$2等變量,那麼這些是什麼意思呢?部落客摘錄一些常用的做下解釋。

$$

Shell本身的PID(ProcessID)

$!

Shell最後運作的背景Process的PID

$?

最後運作的指令的結束代碼(傳回值)

$-

使用Set指令設定的Flag一覽

$*

所有參數清單。如"$*"用「"」括起來的情況、以"$1 $2 … $n"的形式輸出所有參數。

$@

所有參數清單。如"$@"用「"」括起來的情況、以"$1" "$2" … "$n" 的形式輸出所有參數。

$#

添加到Shell的參數個數

$0

Shell本身的檔案名

$1~$n

添加到Shell的各參數值。$1是第1參數、$2是第2參數…

舉例:

#!/bin/bash

#

printf "The complete list is %s\n" "$$"

printf "The complete list is %s\n" "$!"

printf "The complete list is %s\n" "$?"

printf "The complete list is %s\n" "$*"

printf "The complete list is %s\n" "$@"

printf "The complete list is %s\n" "$#"

printf "The complete list is %s\n" "$0"

printf "The complete list is %s\n" "$1"

printf "The complete list is %s\n" "$2