迷,什么都是道理;悟,什么都不是道理。

CentOS   MySQL

导航

CentOS Shell 变量扩展

目录

间接引用 : ${!变量} 
是否为空 : ${变量:-默认值} ${变量:=初始值} ${变量:?提示} ${变量:+默认值}
长度截取 : ${变量:开始位置} ${变量:开始位置:长度}
字符串长度: ${#变量}
顺序删除 : ${变量#字符串} ${变量##字符串} ${变量%字符串} ${变量%%字符串} 
匹对删除 : ${变量/字符串/字符串} ${变量//字符串/字符串}

${!变量名}:引用间接变量

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:02:54 ~ ] 
# a=123

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:02:57 ~ ] 
# b=a

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:02:58 ~ ] 
# echo ${!b}
123

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:03:04 ~ ] 
# eval echo \$$b
123

 

${变量名:-默认值}:若变量为空(或不存在)时,输出默认值。注意变量自身没有被赋值。

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:04:49 ~ ] 
# a=''

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:05:07 ~ ] 
# echo $a

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:05:14 ~ ] 
# echo ${a:-cpu}
cpu

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:21:46 ~ ]
# echo ${a} [ root@stock.data.news.
100 pts/0 2021-01-02/31@6 17:05:26 ~ ] # a=1 [ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:05:31 ~ ] # echo ${a:-cpu} 1

 

${变量:=初始值}:若变量为空(或不存在时),对变量赋予初始值。注意变量自身被赋值。

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:09:42 ~ ] 
# echo $c

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:09:50 ~ ] 
# echo ${c:=cpu}
cpu

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:10:08 ~ ] 
# echo $c
cpu

 

${变量:?提示}:当变量为空(或不存在),输出提示语句

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:13:21 ~ ] 
# a='ok';b=''

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:13:45 ~ ] 
# echo ${a:?var is null}
ok

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:14:03 ~ ] 
# echo ${b:?var is null}
-bash: b: var is null

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:16:07 ~ ]
# abc
-bash: abc: command not found

 

${变量:+默认值}:当变量值不为空时,则输出默认值。注意变量自身没有被赋值。

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:18:40 ~ ] 
# unset a

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:19:05 ~ ] 
# echo ${a:+cpu}


[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:19:21 ~ ] 
# a=linux

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:19:33 ~ ] 
# echo ${a:+cpu}
cpu

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:19:39 ~ ] 
# echo $a
linux

 

${变量:开始位置}

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:21:50 ~ ] 
# unset a

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:31:34 ~ ] 
# a=123456

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:31:40 ~ ] 
# echo ${a:2}
3456

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:31:46 ~ ] 
# echo $a
123456

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:32:28 ~ ] 
# echo ${a:2:1}
3

[ root@stock.data.news.100 pts/0 2021-01-02/31@6 17:32:36 ~ ] 
# echo ${a:2:2}
34

 

posted on 2021-01-02 17:04  3L·BoNuo·Lotus  阅读(88)  评论(0编辑  收藏  举报