shell學習筆記(1)-變數

來源:互聯網
上載者:User

標籤:

1、shell中的變數可以自訂,shell中使用變數時用$

name="shero"
echo "hi ${name}"

[email protected]:/home/shero/shell# ./test2.sh
hi shero

注意,變數名和等號之間不能有空格,這可能和你熟悉的所有程式設計語言都不一樣。同時,變數名的命名須遵循如下規則:

  • 首個字元必須為字母(a-z,A-Z)。
  • 中間不能有空格,可以使用底線(_)。
  • 不能使用標點符號。
  • 不能使用bash裡的關鍵字(可用help命令查看保留關鍵字)。
  • 推薦給所有變數加上花括弧,這是個好的編程習慣。
  • 使用變數的時候才加美元符($)。
  • 定義變數時,變數名不加貨幣符號($)

2、刪除變數

 unset 變數名

eg:

name="shero"
FirstName="huo"
echo "hi $name $FirstName"
unset name
echo "hi $name $FirstName"

執行結果:

[email protected]:/home/shero/shell# ./test2.sh
hi shero huo
hi huo

3、變數可以被重新定義:

name="shero"
FirstName="huo"
echo "hi $name $FirstName"
#unset name
#echo "hi $name $FirstName"
name="lucy"
echo "hi $name"

執行結果:

[email protected]:/home/shero/shell# ./test2.sh
hi shero huo
hi lucy

4、變數可以設定成唯讀變數

name="shero"
FirstName="huo"
echo "hi $name $FirstName"
#unset name
#echo "hi $name $FirstName"
readonly name
name="lucy"
FirstName="Lee"
echo "hi ${name} ${FirstName}"

執行結果:

[email protected]:/home/shero/shell# ./test2.sh
hi shero huo
./test2.sh: line 7: name: readonly variable
hi shero Lee

 

變數類型

運行shell時,會同時存在三種變數:

1) 局部變數

局部變數在指令碼或命令中定義,僅在當前shell執行個體中有效,其他shell啟動的程式不能訪問局部變數。

2) 環境變數

所有的程式,包括shell啟動的程式,都能訪問環境變數,有些程式需要環境變數來保證其正常運行。必要的時候shell指令碼也可以定義環境變數。

3) shell變數

shell變數是由shell程式設定的特殊變數。shell變數中有一部分是環境變數,有一部分是局部變數,這些變數保證了shell的正常運行

shell學習筆記(1)-變數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.