gpt4 book ai didi

linux - Bash While 循环未结束

转载 作者:可可西里 更新时间:2023-11-01 11:46:06 25 4
gpt4 key购买 nike

我在玩 bash 编程。我写了一个简单的 bash 程序,它接受读者的输入。如果读者键入字符串“bye”,则 while 循环结束。所以这个程序很简单我写了这样的东西

#!/bin/sh
inputString="hello"
while [ inputString != "bye" ]
do
echo "Please write something (bye to quit)"
read inputString
echo "You typed : ${inputString}"
done

除非用户一次输入两个单词,否则它会完美运行。

如果用户输入这样的内容

bye bye

程序崩溃,出现以下错误

./WhileLoop.sh: 5: [: bye: unexpected operator

如何修改代码使程序可以接受多个输入?

最佳答案

while 的条件下,将双引号括在 inputString 周围。如果没有双引号,如果您的变量为空,则会引发错误。

更新:

脚本有错字,在inputString前加上$,进行变量替换:while [ "$inputString"!= "bye"]

关于linux - Bash While 循环未结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25708013/

25 4 0
文章推荐: windows - 在 Windows 批处理文件中的多个命令中使用 powershell 变量
文章推荐: php - 构建快速重定向服务器
文章推荐: java - 如何使用 Spring Boot 在 Redis 中存储 List 类型的值?