首页 > Linux Shell, 操作系统 > SHELL 变量进阶

SHELL 变量进阶

2015年1月27日 发表评论 阅读评论

1.${#var}

查看变量的长度

[test@Server1 shell]$ unset name
[test@Server1 shell]$ name=tom
[test@Server1 shell]$ echo ${name}
tom

如果变量为设置或变量为NULL,则变量的程度为空

[test@Server1 shell]$ unset name
[test@Server1 shell]$ echo ${#name}
0
[test@Server1 shell]$ name=
[test@Server1 shell]$ echo ${#name}
0

2.${var:offset:length}

截取变量

offset 0 表示第一个

[test@Server1 shell]$ unset name
[test@Server1 shell]$ name=tom
[test@Server1 shell]$ echo ${name:0:1}
t

如果省略了length则代表截取到变量的结尾

[test@Server1 shell]$ unset name
[test@Server1 shell]$ name=tom
[test@Server1 shell]$ echo ${name:1}
om

如果offset为负则代表截取变量是从结尾开始的,同时特别注意offset和前面的”:”有一个空格,例如:

[test@Server1 shell]$ unset name
[test@Server1 shell]$ name=tom
[test@Server1 shell]$ echo ${name:-1}
tom
[test@Server1 shell]$ echo ${name: -1}
m

注意:没有空格的返回了整个变量

3.${!var}

相当于${var}存放的指针,获取指针指向的真正变量

[test@Server1 shell]$ name=tom
[test@Server1 shell]$ name2=name
[test@Server1 shell]$ echo ${!name2}
tom

4.${var%patten}

按照patten的匹配模式,截取后面的变量。

如果是%%则按最长匹配原则,相当于正则表达式里的贪婪模式

[test@Server1 shell]$ var=b_syslog
[test@Server1 shell]$ echo ${var%s*}
b_sy
[test@Server1 shell]$ echo ${var%%s*}
b_

*代表任意多个字符

5.${var#patten}

按照patten的匹配模式,截取前面的变量。

如果是##则按最长匹配原则,相当于正则表达式里的贪婪模式

[test@Server1 shell]$ unset var
[test@Server1 shell]$ var=b_syslog
[test@Server1 shell]$ echo ${var#*s}
yslog
[test@Server1 shell]$ echo ${var##*s}
log

6.${var//patent/repalece}

变量替换

[test@Server1 shell]$ name=Tom
[test@Server1 shell]$ echo ${name//T/t}
tom

?代表任意一个字符

[test@Server1 shell]$ echo ${name//?/*}
***

7.BASH4增加了大小写的转换

查看shell版本:

[test@Server1 shell]$ echo ${BASH_VERSION[*]}
4.1.2(1)-release

7.1转大写:${var^patten}

^:将符合patten的首字母转成大写,如果忽略patten则直接将首字母转成大写

^^:将符合patten的字母转成大写,如果忽略patten则直接将字母转成大写

[test@Server1 shell]$ name=tOm
[test@Server1 shell]$ echo ${name^}
TOm
[test@Server1 shell]$ echo ${name^^}
TOM
[test@Server1 shell]$ echo ${name^[tm]}
TOm
[test@Server1 shell]$ echo ${name^^[tm]}
TOM

7.2转小写${var,patten}

,:将符合patten的首字母转成大写,如果忽略patten则直接将首字母转成大写

,,:将符合patten的字母转成大写,如果忽略patten则直接将字母转成大写

[test@Server1 shell]$ unset name
[test@Server1 shell]$ name=TOm
[test@Server1 shell]$ echo ${name,}
tOm
[test@Server1 shell]$ echo ${name,,}
tom
[test@Server1 shell]$ echo ${name,[TO]}
tOm
[test@Server1 shell]$ echo ${name,,[TO]}
tom

分类: Linux Shell, 操作系统 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.