![getopts를 사용하여 bash에서 선택적 매개변수 처리](https://linux55.com/image/182539/getopts%EB%A5%BC%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20bash%EC%97%90%EC%84%9C%20%EC%84%A0%ED%83%9D%EC%A0%81%20%EB%A7%A4%EA%B0%9C%EB%B3%80%EC%88%98%20%EC%B2%98%EB%A6%AC.png)
선택적 매개변수를 사용하여 입력 파일을 처리하는 bash 스크립트가 있습니다. 스크립트는 다음과 같습니다
#!/bin/bash
while getopts a:b:i: option
do
case "${option}"
in
a) arg1=${OPTARG};;
b) arg2=${OPTARG};;
i) file=${OPTARG};;
esac
done
[ -z "$file" ] && { echo "No input file specified" ; exit; }
carry out some stuff
스크립트는 잘 실행되지만 입력 파일을 다음과 같이 지정해야 합니다.
sh script.sh -a arg1 -b arg2 -i filename
-i
다음과 같이 옵션 없이 스크립트를 호출할 수 있기를 원합니다.
sh script.sh -a arg1 -b arg2 filename
입력 파일을 지정하지 않으면 여전히 오류 메시지가 나타납니다. 이를 수행할 수 있는 방법이 있습니까?
답변1
#!/bin/sh -
# Beware variables can be inherited from the environment. So
# it's important to start with a clean slate if you're going to
# dereference variables while not being guaranteed that they'll
# be assigned to:
unset -v file arg1 arg2
# no need to initialise OPTIND here as it's the first and only
# use of getopts in this script and sh should already guarantee it's
# initialised.
while getopts a:b:i: option
do
case "${option}" in
(a) arg1=${OPTARG};;
(b) arg2=${OPTARG};;
(i) file=${OPTARG};;
(*) exit 1;;
esac
done
shift "$((OPTIND - 1))"
# now "$@" contains the rest of the arguments
if [ -z "${file+set}" ]; then
if [ "$#" -eq 0 ]; then
echo >&2 "No input file specified"
exit 1
else
file=$1 # first non-option argument
shift
fi
fi
if [ "$#" -gt 0 ]; then
echo There are more arguments:
printf ' - "%s"\n' "$@"
fi
해당 코드에는 구체적인 내용이 없기 때문에 bash
으로 변경 하겠습니다 .sh
bash
답변2
확장하고 싶다스티븐 차제라스사용하기에 좋은 답변바시즘질문 스타일에 대한 추가 정보, 즉 [ -z "$file" ] && { echo "No input file specified" ; exit; }
-를 사용하는 대신만약에.
#!/bin/bash
unset -v file arg1 arg2
while getopts "a:b:i:" option; do
case "$option" in
a ) arg1="$OPTARG";;
b ) arg2="$OPTARG";;
i ) file="$OPTARG";;
* ) exit 1;;
esac
done
shift "$((OPTIND - 1))"
[ -z "$file" ] && [ "$#" -eq 0 ] && { echo "No input file" >&2; exit 1; }
[ -z "$file" ] && [ "$#" -gt 0 ] && { file="$1"; shift; }
echo "DEBUG: arg 1 is $arg1"
echo "DEBUG: arg 2 is $arg2"
echo "DEBUG: file is $file"
[ "$#" -gt 0 ] && { echo "More arguments"; printf " - %s\n" "$@"; }