Shell使用技巧

几种特殊的替换结构
一、${var:-string}
二、${var:+string}
三、${var:=string}
四、${var:?string}html

总结:
    当var为空或者未定义时:${var:-string}的值为string
    当var不为空时:${var:+string}的值为string
    当var为空或未定义时:${var:=string}从新将string赋值给var
    当var为空或未定义时:${var:?string}则将string输出到stdrr

shell中单引号与双引号的区别:
单引号:告诉shell忽略特殊字符
双引号:解释特殊符号原有的意义shell

example:
[root@deploy scripts]# a="sss"
[root@deploy scripts]# echo $a
sss
[root@deploy scripts]# echo '$a'
$a
[root@deploy scripts]# echo "$a"
ssside

字符串替换
格式:
${parameter/pattern/string}
[root@deploy scripts]# var="hello shell"
[root@deploy scripts]# echo ${var/shell/world}
hello world
字符串截取
格式:
删除匹配前缀
${parameter#word}
${parameter##word}code

删除匹配后缀
${parameter%word} 
${parameter%%word}

# 去掉左边,最短匹配模式
## 去掉左边,最长匹配模式
% 去掉右边,最短匹配模式
%% 去掉右边,最长匹配模式

example:
    [root@deploy scripts]# var="http://www.baidu.com/index.html"
    [root@deploy scripts]# echo ${var#*/}
    /www.baidu.com/index.html
    [root@deploy scripts]# echo ${var##*/}
    index.html
    [root@deploy scripts]# echo ${var%/*}
    http://www.baidu.com
    [root@deploy scripts]# echo ${var%%/*}
    http:
相关文章
相关标签/搜索