我是bash脚本的新手。我今天写了这个小脚本。当我运行它时,它返回错误:./ test1.sh:第8行:[n!= y]]:找不到命令。我尝试了几种不同的组合,无法让它发挥作用。
#!/bin/bash
function ask_yes_or_no
{
local exitLoop="n"
local answer=""
while ["$exitLoop" != "y"]]
do
read -p "$1 (y/n)? " choice
case "$choice" in
y|Y )
answer="y"
exitLoop="y"
;;
n|N )
answer="y"
exitLoop="y"
;;
esac
done
echo $answer
}
retVal=$(ask_yes_or_no "Do you want to continue")
echo $retVal;
exit 0
答案 0 :(得分:0)
如果您将评论全部放在我的评论中,并在shellcheck online的帮助下,则会出现以下第一个版本:
#!/bin/bash --
function ask_yes_or_no()
{
local exitLoop="n"
local answer=""
while [ "$exitLoop" != "y" ]
do
read -r -p "$1 (y/n)? " choice
case "$choice" in
y|Y )
answer="y"
exitLoop="y"
;;
n|N )
answer="n"
exitLoop="y"
;;
esac
done
echo $answer
}
retVal=$(ask_yes_or_no "Do you want to continue")
echo "$retVal";
exit 0
所以,你的第一次尝试几乎是好的。正如评论中所写, while 条件中有2个结尾]]而不是],并且有重要的空格字符要添加。其余部分来自shellcheck(可以作为命令行安装)。
测试如下:
chmod +x ./myscript.sh
./myscript.sh
Do you want to continue (y/n)? y
y
./myscript.sh
Do you want to continue (y/n)? n
n