2014-02-11 11 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

는 내가 전에이 시도 :

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.

그래서 당신이 원하는 말한다. 매개 변수없이 호출해도 여전히 작동하지 않습니다. ./sc.sh -r /// 오류 : ./sc.sh : 옵션에는 인수가 필요합니다. - – Smugli

+0

@Smugli : 내 편집 참조 – chaos

+0

감사합니다. 이제 제대로 작동합니다! – Smugli

2

매개 변수 번호 ($ 2)를 하드 코딩하지 전에 다른 매개 변수가있을 수 있습니다.

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"