쉘 스크립팅에서 긴 옵션을 사용하는 "적절한 방법"은 getopt GNU 유틸리티를 사용하는 것 입니다. bash 내장 된 getopts 도 있지만 짧은 옵션 만 허용 -t합니다. getopt사용법에 대한 몇 가지 예는 여기 에서 찾을 수 있습니다 .
다음은 귀하의 질문에 어떻게 접근하는지 보여주는 스크립트입니다. 대부분의 단계에 대한 설명은 스크립트 자체에 주석으로 추가됩니다.
#!/bin/bash
# GNU getopt allows long options. Letters in -o correspond to
# comma-separated list given in --long.
opts=$(getopt -o t --long test -- "$*")
test $? -ne 0 && exit 2 # error happened
set -- $opts # some would prefer using eval set -- "$opts"
# if theres -- as first argument, the script is called without
# option flags
if [ "$1" = "--" ]; then
echo "Not testing"
testing="n"
# Here we exit, and avoid ever getting to argument parsing loop
# A more practical case would be to call a function here
# that performs for no options case
exit 1
fi
# Although this question asks only for one
# option flag, the proper use of getopt is with while loop
# That's why it's done so - to show proper form.
while true; do
case "$1" in
# spaces are important in the case definition
-t | --test ) testing="y"; echo "Testing" ;;
esac
# Loop will terminate if there's no more
# positional parameters to shift
shift || break
done
echo "Out of loop"
몇 가지 단순화와 주석 제거를 통해 다음과 같이 요약 할 수 있습니다.
#!/bin/bash
opts=$(getopt -o t --long test -- "$*")
test $? -ne 0 && exit 2 # error happened
set -- $opts
case "$1" in
-t | --test ) testing="y"; echo "Testing";;
--) testing="n"; echo "Not testing";;
esac