## 引言
shell这门语言,作为与Linux交互效率最高的工具,我相信每个code monkey在工作中或多或少都会用到;我今天要讲的是这门语言中最基本的部分——变量。shell中的变量与类C语言差异较大,相信大家看完后都会有所收获。
语法
在shell中,我们可以使用FOO=BAR这样的方式声明变量(注意,这里不能有空格),当使用这种方式声明变量时,变量是没有类型的,或者说变量的类型可以根据上下文自己转换。比如:
a=2334 # Integer.
let "a += 1"
echo "a = $a " # a = 2335
echo # Integer, still.
b=${a/23/BB} # Substitute "BB" for "23".
# This transforms $b into a string.
echo "b = $b" # b = BB35
declare -i b # Declaring it an integer doesn't help.
echo "b = $b" # b = BB35
let "b += 1" # BB35 + 1
echo "b = $b" # b = 1
echo # Bash sets the "integer value" of a string to 0.
c=BB34
echo "c = $c" # c = BB34
d=${c/BB/23} # Substitute "23" for "BB".
# This makes $d an integer.
echo "d = $d" # d = 2334
let "d += 1" # 2334 + 1
echo "d = $d" # d = 2335
declare
我们可以使用shell内置的declare声明变量:
| 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声明一个变量时默认的类型,当我们执行
JAVA_HOME=/usr/default/java
时,JAVA_HOME这个变量的类型是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 |

被折叠的 条评论
为什么被折叠?



