※ 引述《everydate.bbs@ptt.cc (月)》之銘言:
> echo ${變數##內容} 從前面開始刪除符合內容的最長字串
> echo ${變數#內容} 從前面開始刪除符合內容的最短字串
[...]
> 請問有人可以解釋一下 ## 的用法嗎?
> 還是可以用一個比較清楚的用法?謝謝 @@
"info bash" 可得到完整的文件說明,以下節錄前半段:
${parameter##word}
The word is expanded to produce a pattern just as in pathname
expansion. If the pattern matches the beginning of the 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.
重點是 "pattern" 呀。給個範例就知曉其玄機了:
$ $ ./getdev.sh
Give device name : /dev/ttySAC0
ttySAC0
jserv@venux:/tmp/XXX$ cat getdev.sh
#!/bin/bash
echo -e "Give device name : \c"
read DEVICE
echo "${DEVICE##*/}"
$ chmod +x getdev.sh
這個 script 設計來取得使用者輸入 (透過 read) 的字串中,真正的裝置名稱。
因為在 Unix 裡頭,"everything is file",免不了會有多層次的檔案結構,但是
我們只要取出最後的名稱。執行看看:
$ ./getdev.sh
Give device name :
在這個提示後面打入,比方說:
$ ./getdev.sh
Give device name : /dev/ttySAC0
ttySAC0
再試試其他輸入:
$ ./getdev.sh
Give device name : /dev/input/touchscreen
touchscreen
您可以將 "##" 換成 "#" 看看,就知道個別差異在哪 :-)
--
Jim Huang aka "jserv"
Planet OrzLab: http://orzlab.blogspot.com/
website: http://jserv.sayya.org/
blog: http://blog.linux.org.tw/jserv/
--
※ Origin: SayYA 資訊站 <bbs.sayya.org>
◆ From: info.sayya.org