2014-09-20 30 views
2

在'手動循環'部分的http://mywiki.wooledge.org/BashFAQ/035,他們有這個代碼。與* - 匹配未知命令行選項, - ?*模式是否提供了任何優勢?

#!/bin/sh 
# (POSIX shell syntax) 

# Reset all variables that might be set 
file= 
verbose=0 

while :; do 
    case $1 in 
     -h|-\?|--help) # Call a "show_help" function to display a synopsis, then exit. 
      show_help 
      exit 
      ;; 
     -f|--file)  # Takes an option argument, ensuring it has been specified. 
      if [ "$2" ]; then 
       file=$2 
       shift 2 
       continue 
      else 
       echo 'ERROR: Must specify a non-empty "--file FILE" argument.' >&2 
       exit 1 
      fi 
      ;; 
     --file=?*) 
      file=${1#*=} # Delete everything up to "=" and assign the remainder. 
      ;; 
     --file=)   # Handle the case of an empty --file= 
      echo 'ERROR: Must specify a non-empty "--file FILE" argument.' >&2 
      exit 1 
      ;; 
     -v|--verbose) 
      verbose=$((verbose + 1)) # Each -v argument adds 1 to verbosity. 
      ;; 
     --)    # End of all options. 
      shift 
      break 
      ;; 
     -?*) 
      printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2 
      ;; 
     *)    # Default case: If no more options then break out of the loop. 
      break 
    esac 

    shift 
done 

# Suppose --file is a required option. Check that it has been set. 
if [ ! "$file" ]; then 
    echo 'ERROR: option "--file FILE" not given. See --help.' >&2 
    exit 1 
fi 

# Rest of the program here. 
# If there are input files (for example) that follow the options, they 
# will remain in the "[email protected]" positional parameters. 

我想了解從腳本中瞭解這些行。

-?*) 
     printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2 
     ;; 

我一直在使用模式-*來代替未知選項。但是這個腳本使用匹配未知的模式-?*

爲什麼-?*模式提供了優於匹配未知選項的模式-*

+1

單獨的短劃線有時用於表示'從標準輸入讀取', - ?*不會捕獲 – sp2danny 2014-09-20 09:41:29

+0

'?'是shell匹配任意單個字符的shell。 '*'匹配*零個或多個字符。因此' - ?*'強制在破折號後至少有一個字符。 – 2014-09-21 00:47:02

+0

@ sp2danny您的評論非常有幫助。你爲什麼不把它作爲一個單獨的答案發布,以便我可以接受它並關閉這個問題? – 2014-09-21 05:07:04

回答

1

單獨的破折號有時用來表示'從標準輸入讀數',
-?*不會捕捉到。

相關問題