[SWLUG] simple shell in bash not working

Dafydd Walters dafydd at walters-home.net
Fri May 4 11:05:19 UTC 2007


Hi Stephen,

Stephen Constantinou wrote:
>   if [ choice < mid ]
>   then
>    echo " choice is less than mid"
>   else
>    echo " choice is greater than mid"
>   fi
> 
> the output to screen is
>    [stephanos at localhost ShellScripts]$ ./Kaspersky
>    ./Kaspersky: Line 3: mid: No such file or directory
>    choice is greater than mid
>    [stephanos at localhost ShellScripts]$

You certainly do need the $ in front of the variable names in the 'if' 
statement, but you should also be using '-lt' rathen than '<'.

In bash, '<', '>', '==' and '!=' are used to compare strings 
lexicographically (i.e. alphabetically). To compare integer variables 
numerically, use '-lt', '-gt', '-eq' and '-ne'.

In cases like this, I usually declare the variables as being integers as 
well (although in your simple example, it wouldn't actually matter if 
you didn't).

Regards,
Dafydd.

----- snip ----

#!/bin/bash

declare -i choice
declare -i mid

choice=5
mid=7

if [ $choice -lt $mid ]
then
   echo " choice is less than mid"
else
   echo " choice is greater than mid"
fi

----- snip ----



More information about the Swlug mailing list