Linux Shell Scripting ClassRoom Series – 22 September

Topics

  • Operators
  • for
  • case
  • select
  • functions
  • debugging

Operators

  • Refer here for operators

looping strucuture

  • Excercise: Write a shell script to print first 10 numbers
#!/bin/bash
echo 1 2 3 4 5 6 7 8 9 10
  • Rather than hardcording we can use looping constructs
  • We have 3 possible ways
    • for
    • while
    • until
# using for
for index in 1 2 3 4 5 6 7 8 9 10
do
  echo $index
done

# using while 
max_number=10
index=1
while [ $index -le $max_number ]
do
    echo $index
    ((index++))
done

# using until
until [ $index -gt $max_number ]
do
    echo $index
    ((index++))
done
  • Excercise2: Create a script add.sh and pass arguments like ‘./add.sh 1 2 3 4’
#!/bin/bash
result=0
for index in $@
do
  result=$result+$index
done
echo "Result is $result"

Functions

  • Refer here
  • Sample Script
#!/bin/bash
show_contents() 
{
    filename_local=$1
    echo "function argument is $filename_local"
    echo "function arguments are $@"
}

#shell script arguments
otherargs=$@
echo "Shell arguments are $otherargs"
for filename in ["/home/ubuntu/bin/test.sh"]
do
    show_contents $filename 
done

  • Write a shell script which adds first two arguments and multiplies third and fourth argument
Sample Testcases
./math.sh 1 2 3 4

---------Result----------
addition result of (1+2) = 3
multiplication result of (3*4) = 12

./math.sh 1 3
--------Result----------
number of arguments should be 4

Solution:

#!/bin/bash
add()
{
    number1=$1
    number2=$2
    result=$((number1+number2))

    echo "addition result of $number1+$number2 is $result"
}

mul()
{
    number1=$1
    number2=$2
    result=$((number1*number2))
    echo "multiplication result of $number1*$number2 is $result"
}

if [ $# -eq 4 ]
then
    add $1 $2
    mul $3 $4
    exit 0
else
    echo "invalid arguments passed"
    exit 1
fi

  • Functions can be global or local. Functions which are defined in the scripts can be used only in that script.
  • Functions can be made global by defining the function elsewhere for eg ~/.bashrc
  • While executing shell scripts use tracing religiously bash -x <script>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner