shell中的特殊變數

2021-08-14 21:13:26 字數 2622 閱讀 3183

1、$? 表示上乙個命令退出的狀態

示例:

[root@localhost shell]# echo $?

0[root@localhost shell]# readonly a='ac'

[root@localhost shell]# unset a

-bash: unset: a: cannot unset: readonly variable

[root@localhost shell]# echo $?

1[root@localhost shell]#

2、$$ 表示當前程序編號

示例:

[root@localhost shell]# echo $$

1233

[root@localhost shell]#

3、$0 表示當前指令碼名稱

示例:

[root@localhost shell]# vi helloword.sh 

#/bin/bash

echo "hello word"

echo $0~~

~"helloword.sh" 3l, 37c written

[root@localhost shell]# ./helloword.sh

hello word

./helloword.sh

[root@localhost shell]#

4、$n 表示n位置的輸入引數(n代表數字,n>=1)

示例:

[root@localhost shell]# vi helloword.sh 

#/bin/bash

echo "hello word"

echo "hello $1"

echo "hello $2"

~"helloword.sh" 4l, 61c written

[root@localhost shell]# ./helloword.sh csdn shell

hello word

hello csdn

hello shell

[root@localhost shell]#

5、$#   表示引數的個數,常用於迴圈

示例:

[root@localhost shell]# vi helloword.sh 

#/bin/bash

echo "hello word"

for ((i=1;i<=$#;i++))

do a=`eval echo '$'$i`

echo "hello $a"

done

~"helloword.sh" 7l, 97c written

[root@localhost shell]# ./helloword.sh hello word

hello word

hello hello

hello word

[root@localhost shell]#

6、$*和$@ 都表示引數列表 

示例:

[root@localhost shell]# vi helloword.sh 

#/bin/bash

echo $*

echo $@~~

"helloword.sh" 3l, 27c written

[root@localhost shell]# ./helloword.sh hello word

hello word

hello word

[root@localhost shell]#

7、$*與$@區別

(1)、$* 和 $@ 都表示傳遞給函式或指令碼的所有引數,不被雙引號" "包含時,都以$1  $2  …$n 的形式輸出所有引數

(2)、當它們被雙引號""包含時,"$*" 會將所有的引數作為乙個整體,以"$1 $2 … $n"的形式輸出所有引數;"$@" 會將各個引數分開,以"$1" "$2" …"$n" 的形式輸出所有引數

示例:

[root@localhost shell]# vi helloword.sh 

#/bin/bash

i=0j=0

for m in "$*"

do let i++

echo "i= $i--> $m "

done

for n in "$@"

do let j++

echo "j= $j--> $n "

done~~

"helloword.sh" 14l, 124c written

[root@localhost shell]# ./helloword.sh "hello word" "helloshell" 1 2

i= 1--> hello word helloshell 1 2

j= 1--> hello word

j= 2--> helloshell

j= 3--> 1

j= 4--> 2

[root@localhost shell]#

Shell中的特殊變數

感謝csdn社群 linux系統維護與使用區 板塊熱心朋友們的解答,我搞清楚了shell中特殊符號的使用,現在把總結分享一下 1.傳遞到指令碼的引數個數 2.以乙個單字串顯示所有向指令碼傳遞的引數。與位置變數不同,此選項引數可超過9個 3.當前shell的pid 4.後台執行的最後乙個程序的程序id...

Shell中的特殊變數

變數 含義備註 0 當前指令碼的檔名 也就是命令的第乙個位置 n 第n個位置引數 例如 test.sh zcc yyds 0代表.test.sh,1代表zcc,2代表yyds 引數的個數 上乙個例子中引數個數為2 傳遞的所有引數 即上個例子的 1 2 傳遞的所有引數 和 不同在於 如果它們在 內,那...

Shell 指令碼中特殊變數

在shell 指令碼中一些變數會根據環境設定中的值進行初始化,這些變數通常用大寫字母命令 環境變數 說明 home 當前使用者的家目錄 path 環境變數 path ps1 命令提示符,通常是 字元 ps2 二級提示符,通常是 字元 ifs 輸入域分隔符,用來分割單詞的一組字串,他們通常是空格 製表...