Programing

if [] (대괄호)의 "[: 너무 많은 인수"오류의 의미

lottogame 2020. 5. 19. 08:04
반응형

if [] (대괄호)의 "[: 너무 많은 인수"오류의 의미


다음 BASH 셸 오류의 의미를 수정하고 수정하는 간단한 간단한 리소스를 찾을 수 없으므로 조사 한 결과를 게시하고 있습니다.

오류:

-bash: [: too many arguments

Google에 적합한 버전 : bash open square bracket colon too many arguments .

컨텍스트 : 등호, 등호와 같은 간단한 비교 연산자를 사용하는 단일 대괄호의 if 조건은 다음과 같습니다.

VARIABLE=$(/some/command);
if [ $VARIABLE == 0 ]; then
  # some action
fi 

당신이 경우 $VARIABLE공백이나 특수 문자가 포함 된 문자열 및 단일 대괄호가 사용 합니다 (바로 가기 인 test명령), 다음 문자열은 여러 단어 속으로 분할 할 수있다. 이들 각각은 별도의 인수로 취급됩니다.

따라서 하나의 변수가 여러 인수로 나뉩니다 .

VARIABLE=$(/some/command);  
# returns "hello world"

if [ $VARIABLE == 0 ]; then
  # fails as if you wrote:
  # if [ hello world == 0 ]
fi 

공백이나 다른 특수 문자를 포함하는 문자열을 내려 놓는 모든 함수 호출에 대해서도 마찬가지입니다.


쉬운 수정

변수 출력을 큰 따옴표로 묶어 하나의 문자열 (따라서 하나의 인수)로 유지하십시오. 예를 들어

VARIABLE=$(/some/command);
if [ "$VARIABLE" == 0 ]; then
  # some action
fi 

그렇게 간단합니다. 그러나 변수가 빈 문자열이거나 공백 만 포함하는 문자열이 아니라고 보장 할 수 없으면 아래의 "또한주의하십시오 ..."로 건너 뛰십시오.


또는 대체 수정 은 이중 대괄호 ( new test명령 의 바로 가기)를 사용하는 것 입니다.

이것은 bash (및 korn 및 zsh)에만 존재하므로 /bin/shetc로 호출되는 기본 쉘과 호환되지 않을 수 있습니다 .

이는 일부 시스템에서는 콘솔에서 작동하지만cron 모든 구성 방법에 따라 와 같은 다른 곳에서는 호출되지 않을 수 있음을 의미 합니다.

다음과 같이 보일 것입니다 :

VARIABLE=$(/some/command);
if [[ $VARIABLE == 0 ]]; then
  # some action
fi 

명령에 이와 같이 이중 대괄호가 포함되어 있고 로그에 오류가 발생하지만 콘솔에서 작동하는 경우 [[여기에서 제안 된 대안을 바꾸거나 스크립트를 실행할 때 [[aka 를 지원하는 쉘을 사용하는지 확인하십시오 new test.


또한 [: unary operator expected오류를 조심하십시오

"너무 많은 인수"오류가 표시되면 예상치 못한 출력을 가진 함수에서 문자열을 얻는 것입니다. 빈 문자열 (또는 모든 공백 문자열) 을 얻을 수도있는 경우 위의 "빠른 수정"을 사용하더라도 인수가 0으로 처리되고 실패합니다.[: unary operator expected

다른 언어에 익숙하다면 동일한 'gotcha'입니다. 변수의 내용이 평가되기 전에 이와 같은 코드로 효과적으로 인쇄 될 것으로 기대하지 않습니다.

다음 [: too many arguments[: unary operator expected오류 오류를 모두 방지하는 예입니다 . 출력이 비어 있으면 기본값 (이 예에서는 0)으로 큰 따옴표로 묶인 출력을 바꾸십시오 .

VARIABLE=$(/some/command);
if [ "${VARIABLE:-0}" == 0 ]; then
  # some action
fi 

(여기서 $ VARIABLE이 0이거나 비어있는 경우 작업이 수행됩니다. 당연히 다른 동작을 원하면 0 (기본값)을 다른 기본값으로 변경해야합니다)


최종 주 : 이후 [에 대한 바로 가기입니다 test모두가 위 또한 오류 사실이다 test: too many arguments(도하고 test: unary operator expected)


두 개의 변수가 모두 비어 있는지 또는 비어 있지 않은지 테스트하려고 시도하면서 동일한 오류가 발생 하여이 게시물에 충돌했습니다 . 그것은 복합 비교로 밝혀졌습니다 -7.3. 다른 비교 연산자 – 고급 Bash 스크립팅 안내서 ; 그리고 나는 다음을 주목해야한다고 생각했다.

  • 내가 사용 -e은 처음에 "비우기"를 의미 생각; 그러나 이것은 "파일이 존재 함"을 의미합니다- -z변수 (문자열) 테스트
  • String variables need to be quoted
  • For compound logical AND comparison, either:
    • use two tests and && them: [ ... ] && [ ... ]
    • or use the -a operator in a single test: [ ... -a ... ]

Here is a working command (searching through all txt files in a directory, and dumping those that grep finds contain both of two words):

find /usr/share/doc -name '*.txt' | while read file; do \
  a1=$(grep -H "description" $file); \
  a2=$(grep -H "changes" $file); \
  [ ! -z "$a1" -a ! -z "$a2"  ] && echo -e "$a1 \n $a2" ; \
done

edit 12 aug 2013: related problem note:

note that when checking string equality with classic test (single square bracket [), you MUST have a space between the "is equal" operator, which in this case is a singe "equals" = sign (although two equals' signs == seem to be accepted as equality operator too). Thus, this fails (silently):

$ if [ "1"=="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi 
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi 
A

... but add the space - and all looks good:

$ if [ "1" = "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi 
B

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).


Some times If you touch the keyboard accidentally and removed a space.

if [ "$myvar" = "something"]; then
    do something
fi

Will trigger this error message. Note the space before ']' is required.


I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

참고URL : https://stackoverflow.com/questions/13781216/meaning-of-too-many-arguments-error-from-if-square-brackets

반응형