Bash shell basics

How to start bash shell

/bin/bash
echo "Hello world!"
echo "User $USER is on $PWD"  # $USER and $PWD is global variables.

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
# Use (())
echo $((x+y))

# Use bc
echo "$x + $y"| bc -l

# Use scale and bc
echo "sacle = 2; $x + $y"| bc -l

# Use expr
echo $(expr $x + $y )
# bc -> round fuctionality looks having some problems...
# change to use printf 
read x

printf "%.3f" $(echo "scale=4; $x"| bc -l)
# %f -> floating number
# %.xf -> x floating number

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

Read user input

/bin/bash
read name
echo "Welcome $name"

Loops - for

  • Print 1 3 5 7 9
/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

results matching ""

    No results matching ""