Mailinglist Archive: opensuse (1786 mails)

< Previous Next >
Re: [opensuse] question on if clause formatting
On 11/10/2011 7:58 PM, George OLson wrote:
On 11/10/2011 01:39 PM, David Haller wrote:


The syntax is:

if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [
else COMMANDS; ] fi

Note: COMMANDS. Not(!) EXPRESSION.

Ah, ok. that makes sense, why it is better to use 'test' instead of
[ .. ]


Ok, next question. In the script I am writing, I want to take an input,
which is supposed to be a number between 1 and 15. However, if the
operator enters text instead of a number, I want to find it, rather than
letting the interpreter give me an error when it tries compare a string
with a number.

Here is my set of commands:

echo "Please enter a number between 1 and 15"
read entry
if [ "$entry" -ge "1" -a "$entry" -le "15" ]; then
count=$entry
entry=$((entry +1))
else
if [ "$entry" -eq "0" ]; then
count=1
entry=16
else
echo "invalid entry"
exit
fi
fi

I could not find a test option that would do something like the
following after my read entry line and before the initial if statement:
if [[ $entry not an integer ]]; then ...

In reading through man bash, I couldn't find an expression that will do
what I want there either.

Any suggestions?

George

Typeset -i n
read "n?Enter a number from 1 to 15: "
[[ $n -ge 1 -a $n -le 15 ]] || { echo Invalid ; exit 1 ; }

If you needed to allow a legitimate intentional 0 value and treat that differently from an invalid entry that got turned into a 0, then it's a few more lines to test that specially but luckily your example starts at 1 so it's easy to take advantage of the typeset integer feature.

--
bkw
--
To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: opensuse+owner@xxxxxxxxxxxx

< Previous Next >