Tuesday, August 30, 2016

Linux Bash Shell Script Switch Case and For Loop Example


Code Switch Case:

Save the code in a file named "SwitchCaseExample.sh".
#!/bin/bash
#swich case code
echo "yes or no?"
read answer
case "$answer" in
yes) echo "yay";;
no) echo "not";;
y) echo "yes?";;
n) echo "no?";;
*) echo "default case";;
esac
#combined switch case
echo "yes or no?"
read answer
case $answer in
yes|y|Yes|YES) echo "YAY";;
n*|N*) echo "NOT GOOD";;
*) echo "Default Case";;
esac

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 SwitchCaseExample.sh

Code C or, Java Type For Loop:

Save the code in a file named "ForLoopExample.sh".
#!/bin/bash
#I will print in loop
for (( i = 0; i < 5; i++ ))
do
echo "hello word"
done

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 ForLoopExample.sh

No comments: