bash中用户输入的循环

发布于 2025-02-03 16:44:37 字数 308 浏览 3 评论 0原文

我正在尝试为用户输入构建循环,直到获得特定输入,例如我想在输入= 4并打印siiiiii时停止循环 但是问题是程序卡在循环中 如何为循环输入设置新值?

#!/bin/bash

value=4

echo Enter the number:
read $input
while [ $input !=  $value ]
do
    echo "The input must be between 1 and 4"
    read input2
    input = $input2
done

echo siiiiiiiiiiiiiiiiiii

I am trying to build loop for the user input until I get a specific input for example I want to stop the loop when the input = 4 and print siiiiii
but the problem is the program stuck in the loop
how can I set a new value for the loop input ?

#!/bin/bash

value=4

echo Enter the number:
read $input
while [ $input !=  $value ]
do
    echo "The input must be between 1 and 4"
    read input2
    input = $input2
done

echo siiiiiiiiiiiiiiiiiii

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恍梦境° 2025-02-10 16:44:37
#!/bin/bash

value=4

echo Enter the number:
while read input; do
    if [ "$input" = "$value" ]; then break; fi
    echo "The input must be between 1 and 4" >&2
done

echo siiiiiiiiiiiiiiiiiii

您还可以写:

while read input && [ "$input" != "$value" ]; do
    echo "The input must be between 1 and 4" >&2
done

您可能更喜欢使用-eq-ne,因为您正在进行整数比较,因为这会给您其他错误消息。这些错误消息是否有用是一个设计决策:

while read input && ! [ "$input" -eq "$value" ]; do
    echo "The input must be between 1 and 4" >&2
done

您的原始代码的4个主要问题是:未引用变量,在分配input = $ input2上尝试不正确的尝试(您无法围绕周围的空间=),在读取$ input命令中不正确使用$,并且在读取varname 成语。可能还有其他一些小问题,但是这些问题跳出来。

#!/bin/bash

value=4

echo Enter the number:
while read input; do
    if [ "$input" = "$value" ]; then break; fi
    echo "The input must be between 1 and 4" >&2
done

echo siiiiiiiiiiiiiiiiiii

You could also write:

while read input && [ "$input" != "$value" ]; do
    echo "The input must be between 1 and 4" >&2
done

You might prefer to use -eq and -ne since you are doing integer comparisons, as this gives you additional error messages. Whether or not those error messages are useful is a design decision:

while read input && ! [ "$input" -eq "$value" ]; do
    echo "The input must be between 1 and 4" >&2
done

The 4 main issues with your original code are: failure to quote variables, incorrect attempt at the assignment input = $input2 (you cannot have space around the =), incorrect use of $ in the read $input command, and failure to use the standard while read varname idiom. There are probably some other minor issues as well, but those jump out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文