Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Linux Shell 程式設計:變數命名規則與賦值陷阱

Shell 中變數不必事先宣告,但命名要遵守幾條規則:

首字元必須是字母(a-z、A-Z)
中間不可有空白,可用底線(_)
不可使用標點符號
不可使用 bash 保留字(可用 help 查看)

賦值與取值

賦值寫成 變數名=值,取值則在變數名前加 $。注意:賦值時等號兩側不能有空格。

#!/bin/sh
# 對變數賦值
a="hello world" #等號兩邊不可留空格
# 印出變數 a
echo "A is:" $a

存檔為 first,執行 chmod +x first 後以 ./first 執行,輸出為:

A is: hello world

變數名與文字黏在一起時

num=2
echo "this is the $numnd"

這不會輸出「this is the 2nd」而是「this is the」,因為 shell 去找 numnd 這個變數。用花括號界定範圍即可:

num=2
echo "this is the ${num}nd"
輸出:this is the 2nd

注意括號位置,寫成 {$num}nd 會輸出「this is the {2}nd」。

預設是字串賦值

var=1
var=$var+1
echo $var

印出來的是 1+1 而不是 2。要真正做運算有三種寫法:

let "var+=1"
var=$[$var+1]
var=`expr $var +1` #加號兩側務必留空格,否則仍視為字串

前兩種在 bash 下有效,在 sh 下會出錯。let 表示數學運算,expr 用於整數運算且各項以空格隔開,$[] 會先算括號內的表達式再輸出。

此外 Shell 有許多系統自動設定的變數,另外還有透過 export 處理的環境變數,差別在於作用範圍。

Copyright © Linux教程網 All Rights Reserved