您的位置:首页 > 运维架构 > Shell

Shell判断文件是否可在$PATH中找到并且可执行

2017-12-27 22:35 363 查看
#!/bin/bash

#  判断一个文件是否是 可执行文件,且判断能否在PATH中找到,有三种结果
# (1)  找到且可执行                  0
# (2)  找到且不可执行                1
# (3)  没找到                       2

can_find=1
can_run=1

get_result()
{
   res=$(expr $can_find + $can_run)
   echo $res
   return $res
}

in_path()
{
   # 判断是否带了参数
   if [ $# -eq 0 ];
   then
      echo "usage : sh $0 fileName."
      echo "Error 01 : please input a fileName." 
      r=$(get_result)
      #echo "$r"
return $?
   fi
   # 判断文件是否在$PATH里找到
   oldIFS=$IFS
   IFS=":"
   for each_path in $PATH
   do
      #echo "$each_path/$1"
      if [ -e $each_path/$1 ];
      then
         can_find=0
     #echo "$1 can find!"
         if [ -x $each_path/$1 ];
         then
           can_run=0
           echo "$each_path/$1"
         fi
      fi
   done
          
   IFS=$oldIFS

   r_chose=$(get_result)
   case "$r_chose" in
   0 ) echo "success find." ;;
   1 ) echo "can find,can't be running." ;;
   2 ) echo "not found." ;;
   esac
   return $?
}

in_path $1

          res=$(get_result)   res接收的是echo $res,是get_result标准输出的东西,而不是get_result的返回值.

          $?                          上一个被调用函数的返回值

         举例如下:

“sum=$(fsum 2 5)”这种方式,是将标准输出(echo
出来的东子)传递给主程序的变量,而不是返回值!

  脚本执行结果: ret_val = $(sum 10 20)  将sum 10 20 的输出传递给变量ret_val  

另外通过此题目,我也熟悉了case的语法:

Ruby代码  


case  "$variable"  in   

  

 "$condition1"  )  

 command...  

 ;;  

  

 "$condition2"  )  

 command...  

 ;;  

  

esac  

Note    

例子  使用case                                                                                                                     
                                    

Ruby代码  


#!/bin/bash   

# 测试字符串范围.   

  

echo; echo "Hit a key, then hit return."   

read Keypress  

  

case  "$Keypress"  in   

  [[:lower :]]   ) echo "Lowercase letter" ;;  

  [[:upper :]]   ) echo "Uppercase letter" ;;  

  [0-9]          ) echo "Digit" ;;  

  *              ) echo "Punctuation, whitespace, or other" ;;  

esac      #  允许字符串的范围出现在[中括号]中,   

          #+ 或者出现在POSIX风格的[[双中括号中. 
        

exit 0 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell case 函数