Bash : 명령 줄 인수를 구문 분석하는 스크립트에서 eval 및 shift가 사용되는 이유는 무엇입니까?

디미트리오스 데 실라스

이 답변을 찾고 있었을 때 https://stackoverflow.com/a/11065196/4706711 과 같은 매개 변수를 사용하는 방법을 파악 --something하거나 -s답변의 스크립트와 관련하여 몇 가지 질문이 제기되었습니다.

#!/bin/bash
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

우선 shift다음 줄에서 프로그램은 무엇을합니까 ?

        -a|--a-long) echo "Option a" ; shift ;;

그 후 eval다음 행에서 명령 을 사용하는 목적은 무엇입니까?

eval set -- "$TEMP"

위에서 언급 한 스크립트의 줄에 주석을 추가하려고했는데 다음과 같은 응답을 받았습니다.

$ ./getOptExample2.sh  -a 10 -b 20 --a-long 40 -charem --c-long=echi
Param: -a
Option a
Param: 10
Internal error!

그러나 주석을 제거하면 매력처럼 실행됩니다.

Option a
Option b, argument `20'
Option a
Option c, argument `harem'
Option c, argument `echi'
Remaining arguments:
--> `10'
--> `40'
무루

getopt옵션을 구문 분석하는 동안 수행하는 많은 작업 중 하나는 인수를 재정렬하여 옵션이 아닌 인수가 마지막에 나오고 결합 된 짧은 옵션이 분할되도록하는 것입니다. 에서 man getopt:

Output is generated for each element described in the previous section.
Output is done in the same order as the elements are specified  in  the
input,  except  for  non-option  parameters.   Output  can  be  done in
compatible (unquoted) mode, or in such way that  whitespace  and  other
special  characters  within  arguments  and  non-option  parameters are
preserved (see QUOTING).  When the output is  processed  in  the  shell
script,  it  will  seem to be composed of distinct elements that can be
processed one by  one  (by  using  the  shift  command  in  most  shell
languages).

[...]

Normally, no  non-option  parameters  output  is  generated  until  all
options  and  their  arguments  have  been  generated.   Then  '--'  is
generated as a single parameter, and after it the non-option parameters
in  the  order  they were found, each as a separate parameter.

이 효과는 코드에 반영되며, 옵션 처리 루프 모든 옵션 인수 (옵션에 대한 인수 포함)가 먼저 나오고 별도로 오며 마지막으로 옵션이 아닌 인수가 뒤따른다고 가정 합니다.

따라서 TEMP재 배열, 인용, 분할 옵션이 포함되어 있으며 사용 eval set하면 스크립트 인수가 생성됩니다.

shift경우 항상하는 일을 수행합니다. 첫 번째 인수를 제거하고 모든 인수를 이동 합니다 ( $2이제 있던 것이 $1). 이렇게하면 처리 된 인수가 제거되므로이 루프 이후에는 옵션이 아닌 인수 만 남고 $@옵션에 대한 걱정없이 편리하게 사용할 수 있습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관