bash bash中while循环的布尔类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2693732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
boolean type for while loop in bash?
提问by user151841
I have a cron script on a shared web host that occasionally gets killed. I'd like to make a loop in bash that tries again if it gets killed, because most of the time it will make it. I'm having trouble with the syntax for storing a boolean value :P
我在共享网络主机上有一个 cron 脚本,它偶尔会被杀死。我想在 bash 中创建一个循环,如果它被杀死,它会再次尝试,因为大多数时候它都会成功。我在存储布尔值的语法方面遇到问题:P
#!/bin/bash
VAR=0;
while [ $VAR ]; do
if nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql; then
VAR=1;
fi
done
So the script recovers from a killed process okay, but once it's run properly, the new VARvalue doesn't kill the whileloop.
所以脚本可以从一个被杀死的进程中恢复,但是一旦它正常运行,新VAR值就不会终止while循环。
What am I doing wrong?
我究竟做错了什么?
采纳答案by kennytm
Try
尝试
while [ "$VAR" -eq 0 ]; do
0and 1are both considered True because they are not null strings.
0和1都被认为是 True 因为它们不是空字符串。
回答by Jürgen H?tzel
No need to you a helper variable, consider using:
不需要你的辅助变量,考虑使用:
while ! mysqldump .....; do :;done
回答by amertune
You could use /bin/trueand /bin/false. Although while ! mysqldump .....; do :;done(Jürgen H?tzel's solution) would be better in this case, there are other cases when using trueand falseare useful.
你可以使用/bin/true和/bin/false。虽然while ! mysqldump .....; do :;done(Jürgen H?tzel 的解决方案)在这种情况下会更好,但在使用时还有其他情况true并且false很有用。
#!/bin/bash
VAR=true
while $VAR; do
if nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql; then
VAR=false
fi
done
回答by Paused until further notice.
In Bash, you can do a numeric conditional using double parentheses rather than a string conditional, but the logic is inverted:
在 Bash 中,您可以使用双括号而不是字符串条件来执行数字条件,但逻辑是颠倒的:
#!/bin/bash
VAR=1;
while (( VAR )); do
if nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql; then
VAR=0;
fi
done
回答by Rondo
I like 'until' better for this... :
我喜欢“直到”更好...:
i=0
until [ $_done ]; do
echo stuff...;
sleep 1;
(( i++ ));
if [ "$i" -gt 9 ]; then
_done=1
fi
done
i=0
until [ $_done ]; do
echo stuff...;
sleep 1;
(( i++ ));
if [ "$i" -gt 9 ]; then
_done=1
fi
done

