Bash中的Parameter Expansion
parameter expansion的基本形式是${xxxx},常见的有:
${parameter:-word}
如果parameter为null或者被unset,那么取word来扩展结果
${parameter:=word}
如果parameter为null或者被unset,那么将word的值赋值给parameter,其值作为扩展结果。
${parameter:offset:length}
取parameter从offset开始,length长度个字符作为扩展结果
${!xxx}形式,就是indirect expansion,即${!var}会取var变量的值作为一个变量的名字,然后取这个 变量的值来作为扩展结果。但也有例外:
${!
prefix*} 和 ${!
prefix@} 会扩展为以prefix开头的所有的变量名
${!
name[@]} 和 ${!
name[*]} 如果name是数组,会扩展为该数组中包含合法元素的下标。如果不是数组,一般来结果就是0或者null.
还有许多不常用的参见man手册。
以下是一个parameter expansion的例子代码:
#!/bin/bash
# below are some examples for Parameter expansion of bash
set -ex
A1=a1
A2=a2
STR=1122334455
# RAY is an array
RAY[1]=10
RAY[2]=10
RAY[5]=10
# A's value is a var name 'F'
F=haha
A=F
# exceptions to indirection expansion, ie: A* and A@ are expanded to be
# all var names with first character is 'A'. the below two commands are
# identical
echo ${!A*}
echo ${!A@}
# exceptions to indirection expansion, ie: the keys of the valid elements
# in array RAY are printed, here result is 1 2 5
echo ${!RAY[@]}
echo ${!RAY[*]}
# indirection expansion, A's value is F, and var F's value haha is the
# result, take a var's value as a var name and get the new var's value as
# the final result.
echo ${!A}
# take substrings from index 2 based 0, with length 2
echo ${STR:2:2}
阅读(825) | 评论(0) | 转发(0) |