## 引言
shell這門語言,作為與linux互動效率最高的工具,我相信每個code monkey在工作中或多或少都會用到;我今天要講的是這門語言中最基本的部分——變量。shell中的變量與類c語言差異較大,相信大家看完後都會有所收獲。
在shell中,我們可以使用<code>foo=bar</code>這樣的方式聲明變量(注意,這裡不能有空格),當使用這種方式聲明變量時,變量是沒有類型的,或者說變量的類型可以根據上下文自己轉換。比如:
我們可以使用shell内置的<code>declare</code>聲明變量:
option
meaning
-a
variable is an array.
-f
use function names only.
-i
the variable is to be treated as an integer; arithmetic evaluation is performed when the variable is assigned a value (see section 3.4.6).
-p
display the attributes and values of each variable. when -p is used, additional options are ignored.
-r
make variables read-only. these variables cannot then be assigned values by subsequent assignment statements, nor can they be unset.
-t
give each variable the trace attribute.
-x
mark each variable for export to subsequent commands via the environment.
shell支援三種資料類型:字元串、整型、數組。
字元串類型是shell聲明一個變量時預設的類型,當我們執行
時,<code>java_home</code>這個變量的類型是string,
文法
說明
${parameter:-defaultvalue}
get default shell variables value
${parameter:=defaultvalue}
set default shell variables value
${parameter:?”error message”}
display an error message if parameter is not set
${#var}
find the length of the string
${var%pattern}
remove from shortest rear (end) pattern
${var%%pattern}
remove from longest rear (end) pattern
${var:num1:num2}
substring
${var#pattern}
remove from shortest front pattern
${var##pattern}
remove from longest front pattern
${var/pattern/string}
find and replace (only replace first occurrence)
${var//pattern/string}
find and replace all occurrences
<a href="http://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html">howto: use bash parameter substitution like a pro</a>
<a href="http://tldp.org/ldp/abs/html/untyped.html">bash variables are untyped</a>
<a href="http://tldp.org/ldp/bash-beginners-guide/html/sect_10_01.html">types of variables</a>