Shell Script Example

Shell Script Example

1) Script to print "Hello World"

cat>example1.sh
#!/bin/bash
echo "Hello World"

ctrl+d (To save and exit)

chmod a+x example1.sh (To give the execute permission to all)

bash example1.sh  (To execute/run the script)
bash -x example1.sh (To execute/run the script in debug mode)

2) Script to print "Hello World" if logged in user is oracle else print Bye

cat>example2.sh
#!/bin/bash
if [[ $USER = "oracle" ]] then #For Testing string value we use [[ ]]
    echo "Hello World"
else
    echo "Bye"
fi

ctrl+d
chmod a+x example2.sh

bash -x example2.sh

3) Script to print "Hello World" if logged in user is not oracle else print Bye

cat>example3.sh
#!/bin/bash
if [[ $USER != "oracle" ]] then #For Testing string value we use [[ ]]
    echo "Hello World"
else
    echo "Bye"
fi

ctrl+d
chmod a+x example3.sh

bash -x example3.sh

4) Script to print "Hello World" if logged in user is not oracle else print Bye
   also script should run on debug mode

cat>example4.sh
#!/bin/bash -x    #Here "-x" is for debug mode
if [[ $USER != "oracle" ]] then #For Testing string value we use [[ ]]
    echo "Hello World"
else
    echo "Bye"
fi

ctrl+d
chmod a+x example4.sh


5) Print number 10 to 1 by while loop in a line and print "Hello All!!" at the end 
cat>while.sh
count=10
while (( count > 0 ))
do
    echo -e "$count \c"
sleep 1   
(( count -- ))
done
echo -e "\n\n Hello All!!"

ctrl+d
chmod a+x  while.sh
 
6) Write a shell script to take a argument as file, directory or links and list the all files, directories or links accordingly (as per argument) of that directory
cat>example6.sh
#!/bin/bash
dir=`pwd`
if [[ $1 = "directory" ]]
then
    find $dir -maxdepth 1 -type d
elif [[ $1 = "link" ]]
then
    find $dir -maxdepth 1 -type l
elif [[ $1 = "file" ]]
then
    find $dir -maxdepth 1 -type f
else
    echo "Usages : $0 file | directory |link"
fi

ctrl+d
chmod a+x example6.sh

7) Write a shell script for factorial of a number
cat>fact.sh
#!/bin/sh
factorial()
{
  if [ "$1" -gt "1" ]; then
    i=`expr $1 - 1`
    j=`factorial $i`
    k=`expr $1 \* $j`
    echo $k
  else
    echo 1
  fi
}

echo "Enter a number for factorial :"
read x
y=`factorial $x`
echo "Factorial of $x is :- "$y

ctrl+d
chmod a+x fact.sh

2 comments: