program tip

배시 변수 범위

radiobox 2020. 8. 16. 20:03
반응형

배시 변수 범위


마지막 echo문장이 비어있는 이유를 설명해주세요 . XCODEwhile 루프에서 1의 값으로 증가 할 것으로 예상합니다 .

#!/bin/bash
OUTPUT="name1 ip ip status" # normally output of another command with multi line output

if [ -z "$OUTPUT" ]
then
        echo "Status WARN: No messages from SMcli"
        exit $STATE_WARNING
else
        echo "$OUTPUT"|while read NAME IP1 IP2 STATUS
        do
                if [ "$STATUS" != "Optimal" ]
                then
                        echo "CRIT: $NAME - $STATUS"
                        echo $((++XCODE))
                else
                        echo "OK: $NAME - $STATUS"
                fi
        done
fi

echo $XCODE

++XCODE방법 대신 다음 문을 사용해 보았습니다.

XCODE=`expr $XCODE + 1`

또한 while 문 외부에서는 인쇄되지 않습니다. 여기에 변수 범위에 대한 내용이 누락 된 것 같지만 맨 페이지에 표시되지 않습니다.


while 루프로 배관하기 때문에 while 루프를 실행하기 위해 하위 쉘이 생성됩니다.

이제이 자식 프로세스는 환경의 자체 복사본을 가지고 있으며 모든 변수를 부모에게 다시 전달할 수 없습니다 (모든 유닉스 프로세스에서와 같이).

따라서 루프에 배관하지 않도록 구조를 변경해야합니다. 또는 예를 들어 함수에서 실행 echo하고 하위 프로세스에서 반환하려는 값을 실행할 수 있습니다 .

http://tldp.org/LDP/abs/html/subshells.html#SUBSHELL


문제는 파이프와 함께 결합 된 프로세스가 서브 쉘에서 실행된다는 것입니다 (따라서 자체 환경이 있음). 내부에서 일어나는 while일은 파이프 외부에 영향을 미치지 않습니다.

파이프를 다음과 같이 다시 작성하여 특정 예를 해결할 수 있습니다.

while ... do ... done <<< "$OUTPUT"

또는 아마도

while ... do ... done < <(echo "$OUTPUT")

이것도 작동합니다 (echo와 while이 동일한 서브 쉘에 있기 때문에) :

#!/bin/bash
cat /tmp/randomFile | (while read line
do
    LINE="$LINE $line"
done && echo $LINE )

하나 더 옵션 :

#!/bin/bash
cat /some/file | while read line
do
  var="abc"
  echo $var | xsel -i -p  # redirect stdin to the X primary selection
done
var=$(xsel -o -p)  # redirect back to stdout
echo $var

편집 : 여기에서 xsel은 요구 사항입니다 (설치). 또는 xclip : xclip -i -selection clipboard대신xsel -i -p


 #!/bin/bash
 OUTPUT="name1 ip ip status"
+export XCODE=0;
 if [ -z "$OUTPUT" ]
----

                     echo "CRIT: $NAME - $STATUS"
-                    echo $((++XCODE))
+                    export XCODE=$(( $XCODE + 1 ))
             else

echo $XCODE

이러한 변경 사항이 도움이되는지 확인


Another option is to output the results into a file from the subshell and then read it in the parent shell. something like

#!/bin/bash
EXPORTFILE=/tmp/exportfile${RANDOM}
cat /tmp/randomFile | while read line
do
    LINE="$LINE $line"
    echo $LINE > $EXPORTFILE
done
LINE=$(cat $EXPORTFILE)

I got around this when I was making my own little du:

ls -l | sed '/total/d ; s/  */\t/g' | cut -f 5 | 
( SUM=0; while read SIZE; do SUM=$(($SUM+$SIZE)); done; echo "$(($SUM/1024/1024/1024))GB" )

The point is that I make a subshell with ( ) containing my SUM variable and the while, but I pipe into the whole ( ) instead of into the while itself, which avoids the gotcha.

참고URL : https://stackoverflow.com/questions/124167/bash-variable-scope

반응형