英文:
I am writing a bash program that terminate program if entered number is over 100 and I used if [ $a -gt 100 ] (enter) exit 0 what wrong with this?
问题
但是退出语句不起作用
我希望程序在我输入一个大于100的数字时停止执行
英文:
if [ $a -lt 7 ] || [ $a -gt 77 ]
then
echo "follow instructions"
elif [ $a -gt 100 ]
echo "invalid"
exit 0
fi
but the exit statement isnt working
i was expecting the program to stop executing if I enter a number -gt 100
答案1
得分: 3
Two things:
-
当
a > 100
为真时,a > 77
也为真。 -
当
if
子句为真时,elif
甚至不会被评估。
Consider instead:
#!/usr/bin/env bash
# ^^^^- 请注意,使用 bash 运行此脚本,而不是 sh
if (( a > 100 )); then
echo "无效" >&2
exit 1
elif (( a < 7 || a > 77 )); then
echo "遵循指示" >&2
fi
英文:
Two things:
-
When
a > 100
is true,a > 77
is also true. -
When an
if
clause is true, anelif
is not even evaluated.
Consider instead:
#!/usr/bin/env bash
# ^^^^- note, run this with bash, not sh
if (( a > 100 )); then
echo "invalid" >&2
exit 1
elif (( a < 7 || a > 77 )); then
echo "follow instructions" >&2
fi
答案2
得分: 1
条件范围没有意义。
- 你将(a < 7)或(a > 77)作为正案例。
- 然而,(a > 77)正案例与(a > 100)负案例重叠。
- 同时,程序没有说明当(a >= 7 并且 a <= 77)时会发生什么?
为什么你希望程序在输入无效时退出?通常,程序会验证输入并重复询问,直到获得一个值。你没有展示用户输入代码。以下尝试展示用户带验证的输入,并尝试遵守你的完成和退出条件:
#!/bin/bash
while [ 1 == 1 ];
do
echo -n "输入一个数字:"
read a
if ! [[ "$a" =~ ^[0-9]*$ ]]; then
echo "不是数字,请重试。"
continue
fi
if (( a > 100 )); then
echo "找到终止条件。"
exit 1
fi
if (( a < 7 || a > 77 )); then
echo "找到有效数字。"
break
fi
echo "找到无效数字。请重试。"
done
echo "你输入的是:$a"
以上是该程序的样本运行:
$ ./script.sh
输入一个数字:afdafdsa
不是数字,请重试。
输入一个数字:fdaslkf;daslf;ds
不是数字,请重试。
输入一个数字:55
找到无效数字。请重试。
输入一个数字:1234
找到终止条件。
$ ./script.sh
输入一个数字:3
找到有效数字。
你输入的是:3
$
英文:
The conditional ranges do not make sense.
- You have (a < 7) or (a > 77) as the positive case.
- However, the (a > 77) positive case overlaps with (a > 100) negative case.
- Also, the program does not clarify what happens when (a >= 7 and a <= 77)?
Why would you want the program to exit on invalid input? Typically, a program validates input and asks repeatedly until it gets a value? You do not show the code where the user enters input. Below attempts to show both the user input with validation and tries to honor your completion and exit conditions:
#!/bin/bash
while [ 1 == 1 ];
do
echo -n "Enter a number: "
read a
if ! [[ "$a" =~ ^[0-9]*$ ]]; then
echo "Not a number, try again."
continue
fi
if (( a > 100 )); then
echo "Termination condition found."
exit 1
fi
if (( a < 7 || a > 77 )); then
echo "Valid number found."
break
fi
echo "Invalid number found. Try again."
done
echo "You typed: $a"
Here are sample runs of the above program:
$ ./script.sh
Enter a number: afdafdsa
Not a number, try again.
Enter a number: fdaslkf;daslf;ds
Not a number, try again.
Enter a number: 55
Invalid number found. Try again.
Enter a number: 1234
Termination condition found.
$ ./script.sh
Enter a number: 3
Valid number found.
You typed: 3
$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论