#!/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
#!/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"
下面是上述程序的运行示例:
$ ./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
$
2条答案
按热度按时间h79rfbju1#
两件事:
a > 100
为真时,a > 77
也为真。if
子句为true时,甚至不计算elif
。请考虑以下情况:
jq6vz3qz2#
条件范围没有意义。
为什么要让程序在输入无效时退出?通常,程序会反复验证输入并询问,直到得到一个值。不显示用户输入的代码。下面尝试显示用户输入的验证,并尝试荣誉您的完成和退出条件:
下面是上述程序的运行示例: