我正在制作一个程序,让用户在运行程序时提供3位数字。如果它没有3个数字,那么我给出一条错误信息。如何测试数字的长度,以及如何将这些数字中的每个数字分配给变量?
提前感谢您的帮助!
我尝试过:grep '^[0-9][0-9][0-9]$'
但这不起作用。
答案 0 :(得分:1)
以下列为出发点。添加更多错误检查以获得练习。
#!/bin/bash
while :
do
read -p "Enter a three digit number or q to quit: " input
if (( input >= 100 && input <= 999)); then
echo "good entry"
digit1=${input:0:1} && echo "digit1 is $digit1"
digit2=${input:1:1} && echo "digit2 is $digit2"
digit3=${input:2:1} && echo "digit3 is $digit3"
elif [[ $input == "q" ]]; then
break
else
echo "bad entry"
fi
done
Enter a three digit number or q to quit: 4256
bad entry
Enter a three digit number or q to quit: 242
good entry
digit1 is 2
digit2 is 4
digit3 is 2
Enter a three digit number or q to quit: 562
good entry
digit1 is 5
digit2 is 6
digit3 is 2
Enter a three digit number or q to quit: q
###program breaks here
答案 1 :(得分:0)
您真的想为用户提交中的每个号码设一个变量吗?
ie - foo_one = 1,foo_two = 2,foo_three = 3?
或者你只是想迭代它们&#34;做某事&#34;与每一个?
这是我刚刚聚集在一起的东西,可以帮助你走上正轨:
#!/bin/bash
die() { printf "%s\n" "$@" 1>&2; exit 1; }
read -p "Enter 3 digit number " num
if [[ "${#num}" -lt 3 ]]; then
die "Error: Please enter at least 3 digits."
else
for (( i=0; i<${#num}; i++ )); do
echo " var $i is ${num:$i:1}"
done
fi
输出:
$ ./sotest.sh
Enter 3 digit number 123
var 0 is 1
var 1 is 2
var 2 is 3
很抱歉,如果这没有帮助。也许您可以提供有关总体目标的更多信息?
答案 2 :(得分:-1)
#!/bin/bash
userInput=$1
if [ $(grep -o "[0-9]" <<< $userInput | wc -l) -ne 3 ] || \
[ $(grep -o "[a-z]" <<< $userInput | wc -l) -gt 0 ] || \
[ $(grep -o "[A-Z]" <<< $userInput | wc -l) -gt 0 ]; then
echo "Provide exactly a 3-digit number. No letters, just Numbers...";
exit 1;
else
digi1=$(grep -o "[0-9]" <<< $userInput | awk 'NR==1{print}');
digi2=$(grep -o "[0-9]" <<< $userInput | awk 'NR==2{print}');
digi3=$(grep -o "[0-9]" <<< $userInput | awk 'NR==3{print}');
echo "Digit-1 is $digi1";
echo "Digit-2 is $digi2";
echo "Digit-3 is $digi3";
fi
输出:
]$ ./test.bash 134
Digit-1 is 1
Digit-2 is 3
Digit-3 is 4