bash中是否有“goto”语句?我知道这被认为是不好的做法,但我需要特别“去”。
当前回答
尽管其他人已经澄清了bash中没有直接的goto等价(并提供了最接近的替代方法,如函数、循环和break),但我想说明如何使用循环加break来模拟特定类型的goto语句。
我发现这种方法最有用的情况是,如果某些条件不满足,我需要返回到一段代码的开头。在下面的例子中,while循环将一直运行,直到ping停止向测试IP发送数据包。
#!/bin/bash
TestIP="8.8.8.8"
# Loop forever (until break is issued)
while true; do
# Do a simple test for Internet connectivity
PacketLoss=$(ping "$TestIP" -c 2 | grep -Eo "[0-9]+% packet loss" | grep -Eo "^[0-9]")
# Exit the loop if ping is no longer dropping packets
if [ "$PacketLoss" == 0 ]; then
echo "Connection restored"
break
else
echo "No connectivity"
fi
done
其他回答
它确实可能对一些调试或演示需求有用。
我发现Bob Copeland解决方案http://bobcopeland.com/blog/2012/10/goto-in-bash/优雅:
#!/bin/bash
# include this boilerplate
function jumpto
{
label=$1
cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
eval "$cmd"
exit
}
start=${1:-"start"}
jumpto $start
start:
# your script goes here...
x=100
jumpto foo
mid:
x=101
echo "This is not printed!"
foo:
x=${x:-10}
echo x is $x
结果:
$ ./test.sh
x is 100
$ ./test.sh foo
x is 10
$ ./test.sh mid
This is not printed!
x is 101
还有一种能力可以达到预期的结果:命令陷阱。例如,它可以用于清理目的。
如果你使用它来跳过一个大型脚本的一部分进行调试(参见Karl Nicoll的评论),那么If false可能是一个很好的选择(不确定“false”是否总是可用,对我来说它在/bin/false中):
# ... Code I want to run here ...
if false; then
# ... Code I want to skip here ...
fi
# ... I want to resume here ...
当需要提取调试代码时,困难就出现了。“if false”结构是相当直接和容易记住的,但你如何找到匹配的fi?如果您的编辑器允许您阻止缩进,那么您可以缩进被跳过的块(然后当您完成时,您将希望将其放回)。或者fi线上的注释,但它必须是你能记住的东西,我怀疑这是非常依赖于程序员的。
你可以在bash中使用case来模拟goto:
#!/bin/bash
case bar in
foo)
echo foo
;&
bar)
echo bar
;&
*)
echo star
;;
esac
生产:
bar
star
我找到了一种使用函数的方法。
例如,您有3个选择:A、B和C。A和Bexecute一个命令,但是C给您更多信息,并再次将您带到原始提示符。这可以使用函数来完成。
请注意,由于包含demoFunction函数的那一行只是设置了函数,因此需要在脚本之后调用demoFunction,以便函数能够实际运行。
您可以通过编写多个其他函数并在需要“GOTO”shell脚本中的其他位置时调用它们来轻松地适应这一点。
function demoFunction {
read -n1 -p "Pick a letter to run a command [A, B, or C for more info] " runCommand
case $runCommand in
a|A) printf "\n\tpwd being executed...\n" && pwd;;
b|B) printf "\n\tls being executed...\n" && ls;;
c|C) printf "\n\toption A runs pwd, option B runs ls\n" && demoFunction;;
esac
}
demoFunction