bash主要的變數型別有:
使用者自定義變數、環境變數、位置引數變數、預定義變數
1.使用者自定義變數
linux中預設的變數都是字串型(注意:變數賦值時,「=」前後不能有空格)
[root@hadoop200 ~]# x=1
[root@hadoop200 ~]# y=2
[root@hadoop200 ~]# echo $x+$y
1+2[root@hadoop200 ~]#
變數的疊加
[root@hadoop200 ~]# x=123
[root@hadoop200 ~]# echo "$x"456
123456
[root@hadoop200 ~]#
[root@hadoop200 ~]# x=123
[root@hadoop200 ~]# echo $456
123456
[root@hadoop200 ~]#
2.環境變數
一般建議環境變數寫成大寫,避免與系統命令衝突
使用export將普通變數宣告為環境變數,普通變數只能在當前bash中訪問,環境變數可以在當前bash和其所有子bash中訪問到。
[root@hadoop200 ~]# x=123
[root@hadoop200 ~]# export x
[root@hadoop200 ~]# echo $x
123[root@hadoop200 ~]# bash
[root@hadoop200 ~]# echo $x
123[root@hadoop200 ~]#
典型的環境變數如:path(系統預設讀取命令位置)、ps1(命令提示符格式設定)等
3.位置引數變數
$n(n為數字)
$0代表命令本身,$1-$9代表第一到第九個引數,10以上的引數需要用大括號包含
代表命令列中的所有引數,引數為乙個整體
代表命令列中的所有引數,引數區分對待
命令列中的引數個數
[root@hadoop200 desktop]# cat addnum
#!/bin/bash
num1=$1
num2=$2
sum=$(($num1+$num2))
echo $sum
[root@hadoop200 desktop]#
[root@hadoop200 desktop]# ./addnum 10 20
30[root@hadoop200 desktop]#
4.預定義變數
最後一次執行命令的返回狀態。如果值為0則命令執行正確,否則不正確。
[root@hadoop200 desktop]# ls
addnum
[root@hadoop200 desktop]# echo $?
0[root@hadoop200 desktop]# lsa
bash: lsa: command not found
[root@hadoop200 desktop]# echo $?
127[root@hadoop200 desktop]#
當前程序號
[root@hadoop200 desktop]# echo $$
2354
[root@hadoop200 desktop]# ps -ef | grep 2354
root 2354 2352 0 18:25 pts/0 00:00:00 /bin/bash
root 2514 2354 1 18:42 pts/0 00:00:00 ps -ef
root 2515 2354 0 18:42 pts/0 00:00:00 grep 2354
[root@hadoop200 desktop]#
後台執行的最後乙個程序的程序號
5.檢視系統環境變數和所有變數
所有變數
[root@hadoop200 ~]# env
hostname=hadoop200
term=xterm
shell=/bin/bash
hadoop_home=/usr/local/hadoop-2.5.2
histsize=1000
ssh_client=192.168.111.195 50272 22
ssh_tty=/dev/pts/1
...
所有系統環境變數
[root@hadoop200 ~]# set
bash=/bin/bash
bashopts=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepath
bash_aliases=()
bash_argc=()
bash_ar**=()
bash_cmds=()
bash_lineno=()
bash_source=()
...
Linux Shell程式設計 變數
變數即在程式執行過程中他的值是允許改變的量 變數是用一串固定的字元來表示不固定的值的一種方法 變數是一種使用方便的佔位符,用於引用計算機記憶體位址,該位址可以儲存 script 執行的時可更改的程式資訊 在 shell 中變數是不可能永久儲存在系統中的,必須在檔案中宣告 1.環境級變數 只在當前的s...
Linux Shell程式設計的特殊變數
特殊變數 0 正在被執行命令的名字。對於shell指令碼而言,這是被啟用命令的路徑 n 該變數與指令碼被啟用時所帶的引數相對應。n是正整數,與引數位置相對應 1,2.提供指令碼的引數號 所有這些引數都被雙引號引住。若乙個指令碼接收兩個引數,等於 1 2 所有這些引數都分別被雙引號引住。若乙個指令碼接...
Linux shell程式設計之bash變數
bash變數 命名規則 必須以字母下劃線開頭,只能由字母下劃線數字組成。長度不能超過255個字元 變數名在有效的範圍內必須唯一 在bash中,變數的預設型別都是字串 一 使用者自定義變數 使用者自定義的變數。區域性變數,只在當前shell有效。格式 變數名 變數值 例如 x 5 等號兩邊不能有空格 ...