Bash 变量范围 [英] Bash variable scope

查看:31
本文介绍了Bash 变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请向我解释为什么最后一个 echo 语句是空白的?我希望 XCODE 在 while 循环中增加到 1 的值:

Please explain to me why the very last echo statement is blank? I expect that XCODE is incremented in the while loop to a value of 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 方法

I've tried using the following statement instead of the ++XCODE method

XCODE=`expr $XCODE + 1`

它也不会在 while 语句之外打印.我想我在这里遗漏了一些关于变量作用域的内容,但 ol 的手册页没有向我展示.

and it too won't print outside of the while statement. I think I'm missing something about variable scope here, but the ol' man page isn't showing it to me.

推荐答案

因为您正在通过管道进入 while 循环,所以会创建一个子 shell 来运行 while 循环.

Because you're piping into the while loop, a sub-shell is created to run the while loop.

现在这个子进程有自己的环境副本,不能传递任何变量返回到其父级(就像在任何 unix 进程中一样).

Now this child process has its own copy of the environment and can't pass any variables back to its parent (as in any unix process).

因此,您需要重组,以免进入循环.或者,您可以在一个函数中运行,例如,echo 您的值想要从子流程返回.

Therefore you'll need to restructure so that you're not piping into the loop. Alternatively you could run in a function, for example, and echo the value you want returned from the sub-process.

http://tldp.org/LDP/abs/html/subshel​​ls.html#SUBSHELL

这篇关于Bash 变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆