关于${0##*/} 和${0%/*}
生活随笔
收集整理的這篇文章主要介紹了
关于${0##*/} 和${0%/*}
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
${0##*/}? 是什么意思呢?? ?
我們做一個實驗就知道了
新建一個目錄——mkdir -p /usr/school/grade/class/
新建一個文件——touch /usr/school/grade/class/student
在student文件里寫上代碼并保存——? ?
echo $0
echo ${0#*/}
echo ${0##*/}
運行代碼——? sh? /usr/school/grade/class/student
我們會得到三個結果分別是
/usr/school/grade/class/student
usr/school/grade/class/student
student
這個時候再來講解那三條指令
$0,$1,$2 反正前面有一個$美元符號的,都象征著變量,而$0象征本身shell腳本文件的名字,也就是 /usr/school/grade/class/student
最右邊的 / ,象征著你要尋找,你要匹配的東西,在哪里找呢?在文件名字 /usr/school/grade/class/student 里面找
#象征要尋找最左邊的/
##象征要尋找最右邊的/
而*是通配符,象征著任意長度的字符串
所以在##條件下的 */ , 就象征著/usr/school/grade/class/這一段
找到了這一段之后,就把它截取,扔掉,剩下的就是student這個文件名字
所以 ${0##*/} 的作用是尋找一個路徑下的具體文件名字
/usr/school/grade/class/student,就得到 student
再看官方解釋
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern just as in filename expansion (see section 3.5.8 Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the `#' case) or the longest matching pattern (the `##' case) deleted. If parameter is `@' or `*', the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
再舉一個例子
在suse系統上,這個腳本 /sbin/service
擁有ROOT權限,才能夠使用service服務,否則會報錯
lijunda@linux-d5wb:~> /sbin/service
service: only root can use service
service這個東西,就是從上面/sbin/service 經過 echo ${0##*/}得到的
可以cat里面的代碼驗證一下
if test "$(id -u)" -ne 0; then
?? echo "${0##*/}: only root can use ${0##*/}" 1>&2
?? exit 1
fi
我們再看下一個,${0%/*}
先貼出官網解釋
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the `%' case) or the longest matching pattern (the `%%' case) deleted. If parameter is `@' or `*', the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
${0##*/}
${0%/*}
這兩個命令的共同點,都是截取,丟掉,前者扔掉的是? */這部分,后者扔掉的是/*這部分
不同點的地方在于,#是從左邊頭部開始尋找起,%是從尾部開始尋找起(If the pattern matches a trailing portion)
${0%/*} 這個命令,對于/usr/school/grade/class/student,從右邊找起,得到是 /student 這個部分,然后扔掉
如果是¥{0%%/*},找到的就是 /usr/school/grade/class/student
綜上所述
對于同一個文件 /usr/school/grade/class/student
${0%/*}得到前面/usr/school/grade/class
${0##*/}得到的是后面 student
總結
以上是生活随笔為你收集整理的关于${0##*/} 和${0%/*}的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电厂智慧化解决方案,助力电厂高效发电,节
- 下一篇: 在微型计算机中常用的西文字,全国2011