Bash shell basics
How to start bash shell
/bin/bash
echo "Hello world!"
echo "User $USER is on $PWD"
Varibles
- In bash shell, variables name starts with $. For example, variable X can be writen X but using in other part of script you can use it $X.
- Especially, $X means that use the value of variable X.
- In bash shell, unuseful space can make shell throw error. For example, variable X contains "Hello World!" can be written X="Hello World!".
- Using brackets, you can protect your variables from other varibles.[${V}]
/bin/bash
X="Hello world!"
Y="JSKIM"
echo "${X} to ${Y}"
Variables operators
/bin/bash
read X
read Y
echo $(($X + $Y))
Compare Variables
-eq # ==
-ne # !=
-lt # <
-le # <=
-gt # >
-ge # >=
Arithmetic Operations
read x
read y
echo $((x+y))
echo "$x + $y"| bc -l
echo "sacle = 2; $x + $y"| bc -l
echo $(expr $x + $y )
read x
printf "%.3f" $(echo "scale=4; $x"| bc -l)
Conditions
IF Statement
if [ condition ]
then
actions...
elif [ condition ]
then
actions...
else
actions...
fi
read a
read b
read c
if [ $a -eq $b ] || [ $a -eq $c ]
then
if [ $((a*b)) -eq $((c*c)) ]
then #if [ $((a+b)) -eq $((c*2)) ];then
echo "EQUILATERAL"
else
echo "ISOSCELES"
fi
else
echo "SCALENE"
fi
/bin/bash
read name
echo "Welcome $name"
Loops - for
/bin/bash
for X in 1 3 5 7 9
do
echo $X
done
/bin/bash
for X in {1..10..2}
do
echo $X
done
for ((X=1; X<10; X=X+2))
do
echo $X
done