用來檢測輸入的選項$1是否在PATH中的shell指令碼_linux shell

來源:互聯網
上載者:User

今天無意中發現一本挺有意思的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 1ficheckForCmdInPath "$1"case $? in 0 ) echo "$1 found in PATH"         ;; 1 ) echo "$1 not found or not executable"  ;; 2 ) echo "$1 not found in PATH"       ;;esacexit 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。我想這指令碼還有需要完善的地方。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.