天天看点

shell 变量

## 引言

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>