기본 매개변수를 제공하는 매우 간단한 래퍼를 작성하는 방법은 무엇입니까?

기본 매개변수를 제공하는 매우 간단한 래퍼를 작성하는 방법은 무엇입니까?

예를 들어 일부 매개변수가 필요한 프로그램이 있는 경우, program -in file.in -out file.out이러한 매개변수 유무에 관계없이 호출할 수 있고 각 매개변수에 기본값을 사용하는 bash 스크립트를 작성하는 가장 간단한 방법은 무엇입니까?

script -in otherfile달릴 수 있다 program -in otherfile -out file.out,
script -out otherout -furtherswitch달릴 수 있다 program -in file.in -out otherout -furtherswitch, 등등.

답변1

Bash에서 기본값을 정의하는 것은 쉽습니다.

foo="${bar-default}" # Sets foo to the value of $bar if defined, "default" otherwise
foo="${bar:-default}" # Sets foo to the value of $bar if defined or empty, "default" otherwise

매개변수를 처리하려면 간단한 루프를 사용하면 됩니다.

while true
do
    case "${1-}" in
        -in)
            infile="${2-}"
            shift 2
            ;;
        -out)
            outfile="${2-}"
            shift 2
            ;;
        *)
            break
            ;;
    esac
done

program -in "${infile-otherfile}" -out "${outfile-otherout}" "$@"

유용한 자료:

getopt또한 코드를 복잡하고 혼란스럽게 만들 수 있는 많은 특수한 경우를 처리할 수 있는 능력 때문에 사용을 권장합니다 (중요한 예).

답변2

l0b0의 답변은 값을 할당하고 다른 변수의 상태를 확인하여 기본값을 설정하는 방법을 보여줍니다(물론 값을 할당하려는 동일한 변수로 이 작업을 수행할 수도 있음). 같은 것:

: "${foo=bar}" # $foo = bar if $foo is unset
: "${foo:=bar}" # $foo = bar if $foo is unset or empty

답변3

  • 모든 인수( $*) 를 script다음에 program도 전달합니다.
  • 관심 있는 각 매개변수를 확인하고 이미 전달된 매개변수에 있으면 무시하세요. 그렇지 않으면 기본 매개변수 값을 사용하십시오.

샘플 코드

interested_parameter_names=(-in -out)
default_parameter_values=(file.in file.out)

program=echo
cmd="$program $*"

for ((index=0; index<${#interested_parameter_names[*]}; index++))
do
    param="${interested_parameter_names[$index]}"
    default_value="${default_parameter_values[$index]}"
    if [ "${*#*$param}" == "$*" ]   # if $* not contains $param
    then
        cmd="$cmd $param $default_value"
    fi
done

echo "command line will be:"
echo "$cmd"

echo
echo "execute result:"
$cmd

$interested_parameter_names및 에 더 많은 배열 요소를 추가하여 더 많은 기본 매개변수/값을 쉽게 추가할 수 있습니다.$default_parameter_values

샘플 출력

$ ./wrapper.sh -in non-default.txt -other-params
command line will be:
echo -in non-default.txt -other-params -out file.out

execute result:
-in non-default.txt -other-params -out file.out

노트

공백이 포함된 인수를 전달할 때는 인용 \만 하는 것이 아니라 이스케이프 처리해야 합니다. 예:

./script -in new\ document.txt

답변4

늘 그렇듯이 쉬운 방법과 어려운 방법 두 가지가 있습니다. 간단한 것은 다음과 같은 내부 변수를 사용하는 것입니다.

program -in otherfile -out file.out

여기서 변수는

$0 = 스크립트 이름
$1 = -in
$2 = 기타 파일 등

어려운 방법은 사용하는 것입니다 getopt. 더 많은 정보를 찾을 수 있습니다.여기.

관련 정보