#! /bin/bash
if [ $# -lt 2 ]
then
echo "Less than 2 paramaters"
exit
fi
# The below if condition checks if the number contains a decimal point or not.
# Actually in the for-loop below expr used will not work if the number is not an integer. If you try doing "expr 1.1 + 2.2", it'll say something like this: "expr: non-numeric argument"
echo $* | grep -qe "\."
if [ $? -eq 0 ]
then
echo "One of the input in not an integer"
exit
fi
sum=0
for x in $@
do
sum=`expr $sum + $x`
done
echo "The sum is $sum"
well im doing something similar just checking if only a number is entered no letters can be entered. If a number is entered it should continue to the next part of the bash script. If a letter is entered, user has to try again until a number is entered
i think its an until loop but i cant get it to work
read -p "How many tags to enter:" cars
echo $cars | grep "[a-zA-Z]"
if [ $? -eq 1 ]
then
read -p "Please enter car year:" yearmodel
else
read -p"Invalid number. Please re-enter:" $cars
exit
@gangsta
Please let us know exactly what Operating System and version and Shell you are running. The "read -p" is not "read with a prompt string" in POSIX Shell.
uname -a
echo $SHELL
It would really help if you replied to questions posed on your own threads.
Repeatedly posting the same code segment from a much larger script is not good.
Have you read cfajohnson's post?
while true
do
read -p "How many cars to enter: " tot
[ $tot -ge 0 ] 2>/dev/null && break
echo "Invalid number. re-enter"
done
num=0
while [ $num -lt $tot ]
do
read -p "Enter car #$((++num)): " cars[num]
done
num=0
while [ $num -lt $tot ]
do
echo "Car #$((++num)) is ${cars[num]}"
done
or, using for (( )) loops:
while true
do
read -p "How many cars to enter: " tot
[ $tot -ge 0 ] 2>/dev/null && break
echo "Invalid number. re-enter"
done
for((num=1; num<=tot; num++)) {
read -p "Enter car #$num: " cars[num]
}
for((num=1; num<=tot; num++)) {
echo "Car #$num is ${cars[num]}"
}
$ cat gangsta
#!/bin/bash
while true
do
read -p "How many cars to enter: " tot
[ $tot -ge 0 ] 2>/dev/null && break
echo "Invalid number. re-enter"
done
$ ./gangsta
How many cars to enter: two
Invalid number. re-enter
How many cars to enter: -1
Invalid number. re-enter
How many cars to enter: 3
$./gangsta
How many cars to enter: 5
$
@gangsta: What's the purpose of "2>/dev/null" in "[ $tot -ge 0 ] 2>/dev/null && break"? What do you think STDERR would contain upon this conditional check that you want to direct it to /dev/null?
yea same thing for me but i only want it to show "How many cars to enter" the one time after that if a wrong answer is entered it should only be "Invalid number. Re-enter"
#!/bin/bash
is_int()
{
case $1 in
*[!0-9]*|"") return 1 ;;
esac
}
while :
do
read -ep "How many cars to enter: " tot
is_int "$tot" && [ "$tot" -gt 0 ] && break
printf "%s\n" "Invalid number: $tot"\
"Please enter a number greater than 0"\
"Press ENTER to continue"
read
done