cancel
Showing results for 
Search instead for 
Did you mean: 

Shell scripting

SOLVED
Go to solution

Shell scripting

What's the best way to read an integer?

In my scrip, I have the following loop :

# while true
# do
# typeset -i txt
# echo " Enter a value for $2 (min:${5} - max:${6}) [$CurrValue] : \c"
# read txt 2>/dev/null
# if [[ $? -eq 0 ]]
# then
# if [[ $txt = "" ]]
# then
# txt=$CurrValue
# fi
# if [[ $txt -ge $5 && $txt -le $6 ]]
# then
# break
# fi
# fi
# done

with
$2 : Variable name
$5 : Minimum value
$6 : Maximum value

$CurrVal : Actual variable value

Typeset -i --> force to enter an integer

--> BUT if the user want the default value and only press ENTER, the value of $txt is 0 ! What's the best way to avoid this?

Many Thanks.
5 REPLIES
Robin Wakefield
Honored Contributor

Re: Shell scripting

Hi Fr?d?ric,

Try changing the line:

if [[ $txt = "" ]]

to:

if [[ $txt = "" ]] || [[ $txt -eq 0 ]]

Rgds, Robin.
Praveen Bezawada
Respected Contributor

Re: Shell scripting

Hi
As txt is defined as integer type you can just check

if [ $txt -eq 0 ]; then
.
.
fi

...BPK...
Wodisch
Honored Contributor

Re: Shell scripting

Hello Fr?d?ric,

I do recommend quoting variable EVRYWHERE!

so it yould be like
if [ "$txt" = "" ]

and you will be out of trouble...

HTH,
Wodisch
Sridhar Bhaskarla
Honored Contributor
Solution

Re: Shell scripting

#this checks if the input is null or a character
echo "enter your value"
read x
if [ "$x" = "" ]
then
echo you did not type in anything
else
echo "$x + 1" |bc 2>&1 |grep syntax > /dev/null 2>&1
if [ $? = 0 ]
then
echo "You typed in some characters"
exit
fi
fi

#once it is confirmed that the iniput is not a character
#we check it for zero

if [ $x = 0 ]
then
echo "Sorry zero is not allowed"
exit
fi
#Then we can do whatever we want to do with x as it is

do_whatever_you_wanna_do_with_$x
You may be disappointed if you fail, but you are doomed if you don't try

Re: Shell scripting

Many Thanks Sridhar!

The typeset's problem is that he gives 0 if you do not enter anything. If 0 is a correct value (the minimum one for instance), it is not easy :-)))

Better not assign to integer

Bye and thanks to all of you