2014-02-11 76 views
0

我有另一个bash脚本问题,我简直无法解决。这是我简单的脚本显示问题:BASH:带默认参数值的getopts

while getopts "r:" opt; do 
case $opt in 

    r) 
    fold=/dev 
    dir=${2:-fold} 

    a=`find $dir -type b | wc -l` 
    echo "$a" 
    ;; 
esac 
done 

我通过调用它:

./sc.sh -r /bin 

和它的工作,但如果我不给一个参数,它不工作:

./sc.sh -r 

我想/ dev是我的默认参数$ 2在这个脚本。

回答

0

这个工作对我来说:

#!/bin/bash 

while getopts "r" opt; do 
case $opt in 

    r) 
    fold=/dev 
    dir=${2:-$fold} 

    echo "asdasd" 
    ;; 
esac 
done 

删除在getopts的参数冒号(:)。这导致getopt期望一个参数。 (有关getopt的更多信息,请参见here

+0

我尝试过这一点。当我不带参数地调用它时仍然不起作用:./sc.sh -r ///错误:./sc.sh:选项需要参数 - r – Smugli

+0

@Smugli:请参阅我的编辑 – chaos

+0

谢谢。现在它工作得很好! – Smugli

2

之前可能有其他参数,请不要硬编码参数编号($ 2)。

的getopts的帮助表示

When an option requires an argument, getopts places that argument into the shell variable OPTARG.
...
[In silent error reporting mode,] if a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found.

所以,你想:

dir=/dev       # the default value 
while getopts ":r:" opt; do   # note the leading colon 
    case $opt in 
     r) dir=${OPTARG} ;; 
     :) if [[ $OPTARG == "r" ]]; then 
       # -r with required argument missing. 
       # we already have a default "dir" value, so ignore this error 
       : 
      fi 
      ;; 
    esac 
done 
shift $((OPTIND-1)) 

a=$(find "$dir" -type b | wc -l) 
echo "$a"