Francis
Francis

Reputation: 97

bash script if elif statement

keep getting this error when I run the script, not sure what went wrong, this is if elif with or condition statement

line xx: ((: WEST - Very Big=EAST - BIG: syntax error in expression (error token is "WEST - Very Big")

echo "$yn"

if  (($yn=EAST - BIG)) || (($yn=EAST - SMALL))
    then
echo "---------------------------------------------------------------------------" >> /tmp/"$HOSTNAME".log
elif  (($yn=WEST - Very Big)) || (($yn=WEST - Very Small))  
    then
echo "---------------------------------------------------------------------------" >> /tmp/"$HOSTNAME".log
else
echo "---------------------------------------------------------------------------" >> /tmp/"$HOSTNAME".log
    fi

Upvotes: 0

Views: 1305

Answers (1)

cdarke
cdarke

Reputation: 44344

Several issues. The check for equality inside (( )) is == (a single = is an assignment). This is common to many languages.

You are not allowed whitespace inside a variable name (assuming those are variable names). The characters allowed in a variable name are ASCII alphanumerics or an underscore, and the first character cannot be a number.

It is also a bad idea to use all UPPERCASE for your own variable names. The shell sets and uses a large number of UPPERCASE variables itself, and you could stomp on each other's values.

Here is my test version of your code:

yn=42
EAST=52
BIG=100
WEST=45
Very_Big=3
Very_Small=1
HOSTNAME='fred'

# Here I used a variable to avoid repeating myself
# that makes it easier to change the filename later
outfile="/tmp/$HOSTNAME.log"
> "$outfile"    # Zero the file

echo "$yn"

if  (($yn == EAST - BIG )) || (($yn == EAST - SMALL ))
then
    echo "---------------------------------------------------------------------------" >> "$outfile"
elif  (($yn == WEST - Very_Big )) || (($yn == WEST - Very_Small)) 
then
    echo "---------------------------------------------------------------------------" >> "$outfile"
else
    echo "---------------------------------------------------------------------------" >> "$outfile"
fi

Code is much easier to read when you use consistent indentation. To trace how a bash program is running, use -x, for example:

bash -x myscript

Upvotes: 2

Related Questions