linux - 如何在 While 循环中获取用户输入并使用测试条件 -gt 10 和 -lt 100?

标签 linux bash

<分区>

我正在制作一个 bash 脚本,它要求用户输入 10 到 100 之间的数字,然后给出 echo ,说明该数字是太低还是太高。

请原谅我的代码,我是 bash 脚本的新手并且还在学习,我确信我有很多基本的语法错误。

这是代码。

#!/bin/sh
echo "Enter a Number between 10 and 100."
    read num
if ["$num" -gt 10 -a "$num" -lt 100] ; then
    echo "The Number `$num` is just right"

elif ["$num" -lt 10] ; then 
    echo "Number to small"

elif ["$num" -gt 100] ; then
    echo "Number to big"

else 
    echo "Enter In a Number between 10 and 100"
fi

这是我收到的错误消息。

$ ./Num*
./NumGuess.sh: line 7: [: missing `]'
./NumGuess.sh: line 10: [: missing `]'
./NumGuess.sh: line 12: [: missing `]'
Enter In a Number between 10 and 100

我尝试移动 echo "Enter a Number between 10 and 100." 在 while 循环内,但这没有用。循环不会返回到第一个 if 语句,而是在它接受第一个用户输入然后产生错误后关闭。

最佳答案

您的代码看起来不错,但 if 命令需要空格分隔。所以请改变

if ["$num"-gt 10 -a "$num"-lt 100] ;然后

if [ "$num"-gt 10 -a "$num"-lt 100 ] ; then (还有其他 if 语句)。

第二件事是您在第 5 行中使用反引号 echo "The Number $num is just right"。您需要删除这些。你可以开始了 ;)。

Enter a Number between 10 and 100.
3
Number to small
philipp@philipp-mbp ➜  stackoverflow ./test.sh
Enter a Number between 10 and 100.
23
./test.sh: line 5: 23: command not found
The Number  is just right
--> after removing backticks
stackoverflow ./test.sh   
Enter a Number between 10 and 100.
23
The Number 23 is just right

关于linux - 如何在 While 循环中获取用户输入并使用测试条件 -gt 10 和 -lt 100?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942776/

相关文章:

linux - 从 bash 脚本替换文件中的字符串

bash - Bash 模式替换变量扩展中的引号

linux - 检查已经运行的进程是否在 Linux 上重定向了 stdin?

linux - 如何使用cp将文件复制到目录中与一个目录名相同的文件?

bash - 如何在 Bash 变量中存储大括号

linux - Bash脚本在循环中设置变量

bash - 预期脚本 : to perform actions after closing ssh

linux - 将 EBS 卷附加到 EC2 实例

c - fts_children() 不工作

linux - bash 脚本中执行 Postgresql 命令