4 在Shell程式中的使用變數

2021-09-06 10:33:29 字數 1586 閱讀 1583

學習目標

變數的賦值

變數的訪問

變數的輸入

12-4-1 變數的賦值

在shell程式設計中,所有的變數名都由字串組成,並且不需要對變數進行宣告。要賦值給乙個變數,其格式如下:變數名=值。

注意:等號(=)前後沒有空格

例如:x=6

a=」how are you 」

表示把6賦值給變數x,字串「how are you 」賦值給變數a。

12-4-2 訪問變數值

如果要訪問變數值,可以在變數前面加乙個美元符號「$」,例如:

ubuntu@ubuntu:~$ a="how are you  "

ubuntu@ubuntu:~$ echo "he just said:$a"

he just said:how are you 

ubuntu@ubuntu:~$

乙個變數給另乙個變數賦值可以寫成:變數2=$變數1

例如:x=$i,i++可以寫成:i=$i+1

12-4-3 鍵盤讀入變數值

在shell程式設計中,變數的值可以作為字串從鍵盤讀入,其格式為: read 變數

例如:ubuntu@ubuntu:~$ read str

read為讀入命令,它表示從鍵盤讀入字串到str。

例項:編寫乙個shell程式test3,程式執行時從鍵盤讀入乙個目錄名,然後顯示這個目錄下所有檔案的資訊。

分析:存放目錄的變數為directory,其讀入語句為:read directory,顯示檔案的資訊命令為:ls –a 。

ubuntu@ubuntu:/home/study$ vi

test3

#! /bin/sh

echo

"please input name of directory

"read directory

cd $directory

ls -l

ubuntu@ubuntu:/home/study$ chmod +x test3

ubuntu@ubuntu:/home/study$ ./test3

please input name of directory

/home #輸入路徑時需「/」

例項:執行程式test4,從鍵盤讀入x、y的值,然後做加法運算,最後輸出結果。

#! /bin/sh

echo

"please input x y

"read x y

echo

$x $y

z=`expr $x +$y`

echo

"the sum is $z

"

注意:

read x y –>多個變數之間用空格隔開,切忌用逗號(,)

z=`expr $x + $y`

1)、expr 『+』 兩邊有空格

2)、倒引號,表示在被引用的內容要做運算

4 在Shell程式中的使用變數

學習目標 變數的賦值 變數的訪問 變數的輸入 12 4 1 變數的賦值 在shell程式設計中,所有的變數名都由字串組成,並且不需要對變數進行宣告。要賦值給乙個變數,其格式如下 變數名 值。注意 等號 前後沒有空格 例如 x 6 a how are you 表示把6賦值給變數x,字串 how are...

shell中變數的使用

有關環境變數,詳見linux環境變數詳解 test 123 區域性環境變數一般用小寫 export test 123 全域性環境變數一般用大寫 export myname xiao ba wu 變數值有空格,要用單引號圍起來 export test 也可以這樣把前面的區域性變數匯出到全域性 loca...

shell變數的使用

bash 寫shell指令碼第一行 bin bash 臨時路徑的快捷方式 alias hconf cd usr local hadoop etc hadoop 修改永久路徑快捷方式 vim bashrc插入alias hconf cd usr local hadoop etc hadoop shel...