shell編程之變量詳解

bash中的變量的種類

     1.本地變量 : 生效範圍爲當前shell進程;對當前shell之外的其他shell進程,包括當前shell的子shell進程均無效

變量賦值: name='value'

          使用引用value:

(1) 直接寫字符 name="root"

  (2)變量引用 name="$USER" 

(3)命令引用 name=`command`,name=$()

變量引用: ${name},$name

          顯示已定義的所有變量: set 

刪除變量: unset name

     2.環境變量 : 生效範圍爲當前shell進程及其子進程fFs

變量聲明,賦值:

export name ="value"

declare -x name="value"

  變量引用: $name , ${name}

顯示所有環境變量:

export

      env

      printenv    

刪除: unset name

     3.局部變量 : 生效範圍爲當前shell進程中的代碼片段(通常指函數)

     4.位置變量 : $1,$2,...來表示,用於讓腳本代碼中調用通過命令行傳遞給它的參數

     5.特殊變量: 

$? 上一次退出程序的退出值

$0 : 執行的腳本的文件名

$* : 代表""$1c$2c$3c$4"",其中c爲分隔字符,默認爲空格鍵,代表$1 $2 $3 $4

          $@ : 代表"$1" ,"$2 ","$3" ,"$4" 之意,每個變量都是獨立的,一般記憶$@

$*和$@在被雙引號包起來的時候纔會有差異

  在雙引號引起來的情況:

$*: 將所有的參數認爲是一個字段

$@: 所有的參數每個都是獨立的字段

在沒有雙引號的情況下$*和$@是一樣的


示例:判斷給出文件的行數

 linecount="$(wc -l |$1 |cut -d " " -f1)"

echo "$1 has $linecount lines"

實例: 

寫一個腳本測試$*和$@顯示結果的個數

1.$*和$@帶引號

#!/bin/bash
test() {
echo "$#"
}
echo 'the number of parameter in "$@" is '$(test "$@")
echo 'the number of parameter in "$*" is '$(test "$*")

運行結果

[zhang@centos7 shells]$ bash 2.sh  a b c d
the number of parameter in "$@" is 4
the number of parameter in "$*" is 1

2..$*和$@不帶引號

#!/bin/bash
test() {
echo "$#"
}
echo 'the number of parameter in "$@" is '$(test $@)
echo 'the number of parameter in "$*" is '$(test $*)

運行結果

[zhang@centos7 shells]$ bash 2.sh  a b c d
the number of parameter in "$@" is 4
the number of parameter in "$*" is 4

由測試結果可以看出帶引號的$*輸出結果是一個字段而帶引號的$@輸出的參數每個都是獨立的字段


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章