• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

今天无意中发现一本挺有意思的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。我想这脚本还有需要完善的地方。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
验证用户输入的参数合法性的shell脚本发布时间:2022-02-11
下一篇:
linux shell实现转换输入日期的格式发布时间:2022-02-11
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap