001#在PATH中查找程序

验证指定程序是否有效或者能否在PATH目录列表中找到

 1 #!/bin/bash
 2 # 验证指定程序是否有效或者能否在PATH目录列表中找到
 3 
 4 inpath() {
 5   cmd=$1
 6   ourpath=$2
 7   result=1
 8   oldIFS=$IFS
 9   IFS=":"
10 
11   for dir in $ourpath; do
12     if [ -x $dir/$cmd ]; then
13       result=0
14     fi 
15   done
16 
17   IFS=$oldIFS
18   return $result
19 }
20 
21 checkForCmdInPath() {
22   var=$1
23   if [ $var != "" ]; then
24     if [ ${var%${var#?}} = "/" ]; then
25     # 同 ${var:0:1},提取第一个字符
26       if [ ! -x $var ]; then
27         return 1
28       fi
29     elif ! inpath $var "$PATH"; then
30       return 2
31     fi
32   fi
33 }
34 
35 if [ $# -ne 1 ]; then
36   echo "Usage: $0 command" >&2
37   exit 1
38 fi
39 
40 checkForCmdInPath "$1"
41 
42 case $? in
43   0) echo "$1 found in path"
44   ;;
45   1) echo "$1 not found or not executable"
46   ;;
47   2) echo "$1 not found in path"
48   ;;
49 esac
50 exit 0
View Code

 

posted @ 2020-05-18 16:40  bigtree2pingping  阅读(138)  评论(0编辑  收藏  举报