在 bash 4 中的 if 条件内分配变量?
是否可以在 bash 4 中的 if 条件内部分配变量? IE。在下面的函数中,我想将执行 cmd 的输出分配给输出并检查它是否为空字符串 - 两者都在测试条件内。该函数应该输出
“命令返回:栏”
myfunc() {
local cmd="echo bar"
local output=
while [[ -z output=`$cmd` ]];
do
#cmd is failing so far, wait and try again
sleep 5
done
# great success
echo "command returned: $output"
}
为什么会出现上述情况?
我更喜欢使用“set -e”运行脚本 - 这将导致脚本在第一个不在 if/ 中的非 0 返回/退出代码处终止有条件循环。
考虑到这一点,想象一下 cmd 是一个不稳定的命令,可能会以 > 退出。 1 时不时地调用它,直到它成功并得到一些输出。
is it possible to assign variable inside if conditional in bash 4? ie. in the function below I want to assign output of executing cmd to output and check whether it is an empty string - both inside test conditional. The function should output
"command returned: bar"
myfunc() {
local cmd="echo bar"
local output=
while [[ -z output=`$cmd` ]];
do
#cmd is failing so far, wait and try again
sleep 5
done
# great success
echo "command returned: $output"
}
why the above?
i prefer to run scripts with 'set -e' - which will cause script to terminate on first non-0 return/exit code that's not in an if/loop conditional.
with that in mind, imagine cmd is an unstable command that may exit with > 1 from time to time, and I want to keep calling it until it succeeds and i get some output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试这样的操作:
请注意,强烈建议以避免使用
设置-e
。You can try something like this:
Note that it is strongly recommended to avoid the use of
set -e
.我认为你无法在条件中做到这一点
正如 yi_H 指出的那样, if 相当于
如果 [[ ! -z 输出=栏]];
基本上就是
如果 [[ ! -z“输出=栏”]];
所以,你要检查的是字符串“output=bar”是否为空...
所以,output=bar 实际上可以是类似 !@#!@%=== 的东西,而且它仍然可以相同的事情(即,不计算表达式)。您可能必须以某种方式在子 shell 中分配变量,但我不确定这是否有效。
I don't think you would be able to do it in your conditional
As yi_H pointed out, the if is equivalent to
if [[ ! -z output=bar ]];
which in turn is basically
if [[ ! -z "output=bar" ]];
So, all you are checking is if the string "output=bar" is empty or not...
So, output=bar could actually be anything like !@#!@%=== and it would still do the same thing (that is, the expression isn't evaluated). You might have to assign the variable in a subshell somehow, but I'm not sure that would work.
由于分配在那里不起作用,因此您需要一些解决方法。
您可以临时执行
set +e
...Since assignment won't work there, you need some workaroudn.
You could temporary do a
set +e
...您可以使用这种方式...
编辑:这不适用于“set -e”或其他方式,不要使用“set -e”开始。
You could use this way ...
EDIT: This won't work with 'set -e' or other way around, don't use 'set -e' to begin with.