getopts를 사용하여 bash에서 선택적 매개변수 처리

getopts를 사용하여 bash에서 선택적 매개변수 처리

선택적 매개변수를 사용하여 입력 파일을 처리하는 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으로 변경 하겠습니다 .shbash

답변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" "$@"; }

관련 정보