一个检测命令是否存在且可执行的shell
ATTENTION:这里的shell全部都是个人从网上收集过来的比较有意思的shell然后添加一定的个人的分析。
如果有什么错误,或者不足的地方,欢迎批评指正。
此外,欢迎自由转载。
#!/bin/sh
# inpath - verify that a specified program is either valid as-is,
# or can be found in the PATH directory list.
in_path()
{
# given a command and the PATH, try to find the command. Returns
# 0 if found and executable, 1 if not. Note that this temporarily modifies
# the the IFS (input field seperator), but restores it upon completion.
cmd=$1 path=$2 retval=1
oldIFS=$IFS IFS=":"
for directory in $path
do
if [ -x $directory/$cmd ] ; then
retval=0 # if we're here, we found $cmd in $directory
fi
done
IFS=$oldIFS
return $retval
}
checkForCmdInPath()
{
var=$1
# The variable slicing notation in the following conditional
# needs some explanation: ${var#expr} returns everything after
# the match for 'expr' in the variable value (if any), and
# ${var%expr} returns everything that doesn't match (in this
# case just the very first character. You can also do this in
# Bash with ${var:0:1} and you could use cut too: cut -c1
if [ "$var" != "" ] ; then
if [ "${var%${var#?}}" = "/" ] ; then
if [ ! -x $var ] ; then
return 1
fi
elif ! in_path $var $PATH ; then
return 2
fi
fi
}
if [ $# -ne 1 ] ; then
echo "Usage: $0 command" >&2 ; exit 1
fi
checkForCmdInPath "$1"
case $? in
0 ) echo "$1 found in PATH" ;;
1 ) echo "$1 not found or not executable" ;;
2 ) echo "$1 not found in PATH" ;;
esac
exit 0
<span style="color:#3366ff;">Self:</span>${var%${var#?}}
<span style="white-space:pre"> </span><div><span style="white-space:pre"> </span>${var#?}</div><div><span style="white-space:pre"> </span>这个表示的是var这个字串的除了第一个的剩下的部分</div><div><span style="white-space:pre"> </span>${var%xxxxx}</div><div><span style="white-space:pre"> </span>xxxxx代表的是一个字符串、而且这个字符串必须是从var的某个字符串到最后一个字符串的那一部分。这样返回的就是除了xxxxx这个字符串的其余的部分。。。</div><div><span style="white-space:pre"> </span>所以通过</div><div><span style="white-space:pre"> </span>${var%${var#?}}</div><div><span style="white-space:pre"> </span>这样一个操作就可以将var字符串的首字符取出来、</div><div><span style="white-space:pre"> </span>达到相同目的的操作还有</div><div><span style="white-space:pre"> </span>${var:0:1}</div><div><span style="white-space:pre"> </span>cut -c1</div>