欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

用来检测输入的选项$1是否在PATH中的shell脚本

程序员文章站 2022-08-26 16:18:52
今天无意中发现一本挺有意思的shell编程的书,是e文的,内容是101个shell案例,坚持明天看一个,写点心得。 下面是例子001: #!/bin/sh #...

今天无意中发现一本挺有意思的shell编程的书,是e文的,内容是101个shell案例,坚持明天看一个,写点心得。
下面是例子001:

#!/bin/sh
# inpath - verifies that a specified program is either valid as is,
#  or that it 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 ifs (input field separator) 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

这脚本目的是用来检测输入的选项$1是否在path中。


这脚本有几个地方值得注意的:
1)它运用了函数嵌套,在checkforcmdinpath里嵌套了in_path函数。
2)if [ "${var%${var#?}}" = "/" ] 这语句中的${var%${var#?}}是显示变量的第一个字符,也可以用${varname:1:1} 或$(echo $var | cut -c1)替代。
3) elif ! in_path $var $path ; then 这意思是如果in_path $var $path 执行结果不为0的话则
问题:
发现输入 echo , echo_err, /etco_err 都返回正确结果,但输入 /etc/echo_right (存在着执行文件但不在path中)却返回found in path。我想这脚本还有需要完善的地方。