首页 > 代码库 > 变量的操作
变量的操作
变量算术运算
使用${#VAR} 语法将计算一个变量当中字符的数量
[bob in ~] echo $SHELL
/bin/bash
[bob in ~] echo ${#SHELL}
9
[bob in ~] ARRAY=(one two three)
[bob in ~] echo ${#ARRAY}
3
变量的转化
替换
${VAR:-WORD} 如果 VAR 没有定义或者是空值,由WORD 的值替换;否则输出 VAR 的值:
[bob in ~] echo ${TEST:-test}
test
[bob in ~] echo $TEST
[bob in ~] export TEST=a_string
[bob in ~] echo ${TEST:-test}
a_string
[bob in ~] echo ${TEST2:-$TEST}
a_string
如果 (-) 使用等号(=)替换, the value is assigned to the parameter if it does not exist:
[bob in ~] echo $TEST2
[bob in ~] echo ${TEST2:=$TEST}
a_string
以下语法测试一个变量是否存在。如果没有设置,WORD 的扩展打印到标准输出且非交互shell退出。
(与${VAR:-WORD}的区别,${VAR:?WORD}是一个错误,不是一个正常的输出,而前者回正常输出
和${VAR:=WORD})的区别,${VAR:?WORD}不会把word的值赋给var)
证明:
[bob in ~] cat vartest.sh
#!/bin/bash
# This script tests whether a variable is set. If not,
# it exits printing a message.
echo ${TESTVAR:?"There‘s so much I still wanted to do..."}
echo "TESTVAR is set, we can proceed."
[bob in testdir] ./vartest.sh
./vartest.sh: line 6: TESTVAR: There‘s so much I still wanted to do...
[bob in testdir] export TESTVAR=present
[bob in testdir] ./vartest.sh
present
TESTVAR is set, we can proceed.
要从一个变量之中,删除等于 OFFSET 数量的字符,使用这样的语法:
${VAR:OFFSET:LENGTH}
LENGTH 参数定义了在偏移点offset之后第一个字符开始需要保留多少字符。如果 LENGTH 省略,就是用剩余的变量的内容。
[bob in ~] export STRING="thisisaverylongname"
[bob in ~] echo ${STRING:4}
isaverylongname
[bob in ~] echo ${STRING:6:5}
avery
${VAR#WORD}and ${VAR##WORD}
注:这里是这样定义的:ARRAY=(onetwo one three one four),是数组
而这样定义的ARRAY="onetwo one three one four"是一个字符串,数组会对每一个元素操作。
[bobin ~] echo ${ARRAY[*]}
onetwo one three one four
[bobin ~] echo ${ARRAY[*]#one}
twothree four
[bobin ~] echo ${ARRAY[*]#t}
onewo one hree one four
[bobin ~] echo ${ARRAY[*]#t*}
onewo one hree one four
表示对每个元素,从左开始数,直到匹配到t*的最短的为止,截除掉。
[bobin ~] echo ${ARRAY[*]##t*}
oneone one four
表示对每个元素,从左开始数,直到匹配到t*的最长的为止,截除掉。
[bobin ~] echo $STRING
thisisaverylongname
[bobin ~] echo ${STRING%name}
thisisaverylong
替换:
${VAR/PATTERN/STRING}
or
${VAR//PATTERN/STRING}
语法。第一种形式仅仅替换第一个匹配的项目,第二个用STRING替换所有匹配PATTERN的项目。
[bobin ~] echo ${STRING/name/string}
thisisaverylongstring
变量的操作