用来检测输入的选项$1是否在PATH中的shell脚本
今天无意中发现一本挺有意思的shell编程的书,是e文的,内容是101个shell案例,坚持明天看一个,写点心得。
下面是例子001:
#!/bin/sh #inpath-Verifiesthataspecifiedprogramiseithervalidasis, #orthatitcanbefoundinthePATHdirectorylist. in_path() { #GivenacommandandthePATH,trytofindthecommand.Returns #0iffoundandexecutable,1ifnot.Notethatthistemporarilymodifies #theIFS(inputfieldseparator)butrestoresituponcompletion. cmd=$1path=$2retval=1 oldIFS=$IFSIFS=":" fordirectoryin$path do if[-x$directory/$cmd];then retval=0#ifwe'rehere,wefound$cmdin$directory fi done IFS=$oldIFS return$retval } checkForCmdInPath() { var=$1 #Thevariableslicingnotationinthefollowingconditional #needssomeexplanation:${var#expr}returnseverythingafter #thematchfor'expr'inthevariablevalue(ifany),and #${var%expr}returnseverythingthatdoesn'tmatch(inthis #case,justtheveryfirstcharacter.Youcanalsodothisin #Bashwith${var:0:1},andyoucouldusecuttoo:cut-c1. if["$var"!=""];then if["${var%${var#?}}"="/"];then if[!-x$var];then return1 fi elif!in_path$var$PATH;then return2 fi fi } if[$#-ne1];then echo"Usage:$0command">&2;exit1 fi checkForCmdInPath"$1" case$?in 0)echo"$1foundinPATH";; 1)echo"$1notfoundornotexecutable";; 2)echo"$1notfoundinPATH";; esac exit0
这脚本目的是用来检测输入的选项$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中)却返回foundinPATH。我想这脚本还有需要完善的地方。