Shell script: ##*/

2017-12-27  本文已影响12人  louyang
#Verify if current working directory ends with '/xxx'
current_dir=`pwd`
if [ ${current_dir##*/} != 'xxx' ]
then
    echo "Error: Current directory must be end with '/xxx'"
    exit -1
fi

当读到这样一段代码的时候,我们很容易猜到${current_dir##*/}是为了得到最后一级俄目录名,如全路径为/a/b/c/d/e, 则刚才那段代码是为了得到最后一级目录名e.

可是##*/是怎么滤出最后一级目录名的呢?

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
这个网页是shell script的规范,在其中搜索##,可以看到:

${parameter##[word]}
Remove Largest Prefix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the largest portion of the prefix matched by the pattern deleted.

在这段文字的上方,不远处,可以看到Pattern Matching Notation,从中可知,*/是一种匹配方式,等于‘以斜杠结尾的任何字符串’。
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13

这段文字的下方,给出了例子:

${parameter##word}
x=/one/two/three
echo ${x##*/}
three

${string##*/}就是把一个字符串中最后一个斜杠后面的字符串过滤出来。我们来做几个试验:

# VAR="/a/b/c/d/e"
# echo ${VAR##*/}
e
# echo ${VAR##*c}
/d/e
# echo ${VAR##*b}
/c/d/e
练习

现在有一个字符串 S=AAA.BBB.CCC.DDDD,要取出DDDD,该怎么写?

答案:
# S=AAA.BBB.CCC.DDD
# o=${S##*.}
# echo $o
DDD
上一篇 下一篇

猜你喜欢

热点阅读