国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Linux Shell > 正文

用來檢測輸入的選項$1是否在PATH中的shell腳本

2020-07-27 19:01:31
字體:
來源:轉載
供稿:網友

今天無意中發現一本挺有意思的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。我想這腳本還有需要完善的地方。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 儋州市| 石景山区| 池州市| 崇左市| 天等县| 天峻县| 壶关县| 石首市| 德安县| 长乐市| 西丰县| 大荔县| 高密市| 金平| 宜都市| 永和县| 美姑县| 章丘市| 噶尔县| 荣成市| 金华市| 综艺| 积石山| 永善县| 甘洛县| 钟山县| 西华县| 罗田县| 浮山县| 巴中市| 郓城县| 海兴县| 内黄县| 河曲县| 岑巩县| 东海县| 彩票| 六枝特区| 铜鼓县| 宁河县| 垫江县|