在 shell 脚本中打印命令名称

printing command name in shell script

#!/bin/bash

cmdname=${0##*/} 
tmplogfile="/tmp/."$cmdname".log"

echo $cmdname
exit 0

我有上面的 shell 脚本来完成一些任务。 我不明白 ${0##*/} 在这里的意思。我将 ${0##*/} 更改为 [=14=],结果是一样的。有人能告诉我额外的是什么 ##*/ 意思是?

谢谢。

这是一个shell变量替换符号,用于删除匹配##之后表达式的最大前缀模式。该表达式是 shell 模式而不是正则表达式。在这种情况下,它会删除 $0 中以 / 结尾的最长前缀。例如,对于下面的脚本:

/home/user/> cat /home/user/script
echo 'Value of [=12=]      ' : [=12=]
echo 'Value of ${0##*/}' : ${0##*/}

/home/user/> sh script
Value of [=12=]       : script
Value of ${0##*/} : script

/home/user/> sh /home/user/script
Value of [=12=]       : /home/user/script
Value of ${0##*/} : script

来自FreeBSD sh manpage

${parameter##word}

Remove Largest Prefix Pattern.  The word is expanded to produce a
pattern.  The parameter expansion then results in parameter, with
the largest portion of the    prefix matched by the pattern deleted.

虽然这是 FreeBSD sh 联机帮助页,但同样适用于 shell 周围的所有 Bourne。