'getopts'에 해당되는 글 1건

스크립트 실행시 "-a" 와 같이 옵션을 줄 때, 이를 getopts로 받는 방법 예시

 

test.sh

#!/bin/bash

while getopts abc: arguments 2> /dev/null # 에러출력을 감춘다. "c:"는 c 옵션에는 인자가 필수라는 의미.
do
        case "$arguments" in
                "a")
                        echo "-a option used.";
                        ;;
                "b")
                 	echo "-b option used.";
                        ;;
                "c")
                        echo "-c option used.";
                        echo "OPTARG ===> $OPTARG."; # OPTARG 특수변수는 옵션의 인자로 넘어온 값을 담고있다.
                        ;;
                "?")
                        echo "Usage : opt4 [-ab] [-c argument]";
                        exit 1;
                        ;;
        esac
done
echo "the number of argument is $((OPTIND-1)) ..." # OPTIND 특수변수는 명령줄의 스크립트명(여기서는 ./test.sh)도 포함한 전체 인자의 갯수이다.
# ((OPTIND-1)) 은 산술연산을 의미하고, 이를 다시 변수참조로 받기 위해 $를 앞에 붙여준 듯.

 

./test.sh -a -b -c centos 실행결과

-a option used.
-b option used.
-c option used.
OPTARG ===> centos.
the number of argument is 4 ...

 

./test.sh -abc centos 실행결과

-a option used.
-b option used.
-c option used.
OPTARG ===> centos.
the number of argument is 2 ...

 

블로그 이미지

망원동똑똑이

프로그래밍 지식을 자유롭게 모아두는 곳입니다.

,