Thursday 3 October 2013

Bash Exercise - 1

Script 1: Add two numbers.
#!/bin/bash ---> Shebang Header to identify the shell
a=4 ---> Define variable 'a'
b=5 ---> Define variable 'b'
let sum=$a+$b ---> Add the numbers which are contained by the variables
echo $sum ---> Print the sum value

Script 2: Add two numbers in various methods.
#!/bin/bash
echo enter one number
read a
echo enter another number
read b

# first method
sum=$(($a+$b))
echo the sum is $sum

#second method
sum=$[$a + $b]
echo the sum is $sum

#third method
sum=`expr $a + $b`
echo the sum is $sum

Script 3: Declaration of variables.
#!/bin/bash
declare -i a=20 c=5
declare -i b=30
declare -i sum
sum=$a+$c
echo $sum

Script 4: Performing a backup with tar.
#!/bin/bash
of=/misc/backup-$(date +%y%m%d).tar
tar -czf $of /home


Script 5: Break or ignore specified execution.
LIMIT=19 # Upper limit
echo
echo "Printing Numbers 1 through 20 (but not 3 and 11)."
a=0
while [ $a -le "$LIMIT" ]
do
a=$(($a+1))
if [ "$a" -eq 3 ] || [ "$a" -eq 11 ] # Excludes 3 and 11.
then
continue # Skip rest of this particular loop iteration.
fi
echo -n "$a " # This will not execute for 3 and 11.
done

No comments :

Post a Comment