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:
相關文章
相關標籤/搜索