Tuesday, August 30, 2016

Linux Bash Shell Script Expression Evaluation Examples


How the code below works:

This just an example of expression evaluation in different ways. Also equality and even odd checking in a different way.

Input:

It asks for an input to check if the number is even or odd.

Code for Expression Evaluation Example:

Save the code in a file named "ExpressionEvaluation.sh".
#!/bin/bash
# Do not use space before and after equal sign.
a=1
b=3
sum=`expr $a + $b`
sum=$(( $sum + 5 ))
echo $sum
# If condition, must be closed with fi
a=2
b=2
if [ $a -eq $b ];then
echo "match"
else
echo "not match"
fi
# Check if even
read input
two=2
val=$(( $input / $two ))
val=$(( $val * $two ))
#echo $val
if [ $val -eq $input ];then
echo "Even"
else
echo "Odd"
fi

Running the Code:

Just type the code below in terminal. Make sure to cd into that directory if you have not opened the terminal in that directory.

bash ExpressionEvaluation.sh

No comments: