我的Bash脚本存在问题,脚本本身工作正常,但我正在尝试整理它,但我找不到/想到一个方法作为" goto"命令,是的,我是Linux Bash的新手。
我的代码是:
echo "What is the street road?"
read road
echo "What is the address ?"
read address
echo "User is set as: $road"
echo "Address has been set as: $address"
while true; do
read -p "Is this correct? " yn
case $yn in
[Yy]* ) break;;
[Nn]* ) exit;;
* ) break;;
esac
done
当用户输入" n"该脚本将退出自己,但我正在尝试整理它,所以它只会在这里重新循环。因此,如果用户输入" n"它会再次重新询问他们的道路和地址。
我知道.bat你可以做到 :一个 转到:A (或类似的东西!)但在Bash我不知道该怎么做?
谢谢大家!
答案 0 :(得分:3)
我建议你在GNU bash中使用它:
#!/bin/bash
until [[ $yn =~ ^[Yy]$ ]]; do
read -p "What is the street road? " road
read -p "What is the address ? " address
echo "User is set as: $road"
echo "Address has been set as: $address"
read -p "Is this correct? " yn
done
# continue with your code here
答案 1 :(得分:0)
我会像这样重写你的剧本:
ask () {
echo "$1"
read answer
while true; do
read -p "Is this correct? " yn
case $yn in
[Yy]* ) break;;
[Nn]* ) exit;;
* ) break;;
esac
done
eval "$2='$answer'"
}
ask "What is your street?" street
ask "What is the address?" address
echo "Your address has been set to $address $street"
就像我在您对您的问题的评论中提到的那样,在任何语言中使用goto
通常被视为不良格式(因为它导致难以调试的代码,除了非常具体情况),bash
does not have a goto
like you find in other languages无论如何。如果您发现自己编写的代码需要goto
,请花一点时间,从键盘向后倾斜,然后重新评估一下您的前提。 99.999%的时间,你会发现你并不真正需要它,并且有一种结构化的编程方法可以更加巧妙地完成同样的事情。
答案 2 :(得分:0)
你可以激进:
ok=no
while read -p "What is the street road? " road &&
read -p "What is the address? " address &&
echo "Road is set to: $road" &&
echo "Address has been set as: $address" &&
read -p "Is this correct? " yn
do
case $yn in
([Yy]*) echo "Great!"; ok=yes; break;;
([Nn]*) echo "OK - then try again";;
(*) echo "Didn't understand that - it did not look like Y or N";;
esac
done
if [ "$ok" = "yes" ]
then : OK to use answers
else : Do not use answers
fi
这利用了这样一个事实,即您可以将任意命令列表作为条件'在while
循环中。我已将这些命令与&&
一起链接,因此它们都必须成功,但您可以拥有独立的命令,在这种情况下,最后一个是重要的命令。我还利用read -p 'prompt' var
符号表示初始值以及“这是正确的”#39;之一。
示例对话:
$ bash prompt.sh
What is the street road? California
What is the address? 1189
Road is set to: California
Address has been set as: 1189
Is this correct? n
OK - then try again
What is the street road? California Ave
What is the address? 2291
Road is set to: California Ave
Address has been set as: 2291
Is this correct? y
Great!
$
答案 3 :(得分:0)
有点不典型,但你可以这样做:
#!/bin/sh
while
read -p 'What is the street road? ' road
read -p 'What is the address ? ' address
echo "User is set as: $road"
echo "Address has been set as: $address"
read -p "Is this correct? " yn
case $yn in
[Yy]* ) false;;
* ) true;;
esac
do
:
done
echo "User is set as: $road"
echo "Address has been set as: $address"