Shell Scripting Linux
Shell Scripting Linux
#! /bin/bash
The path of the bash program can vary. We will see later how
to identify it.
Execution rights
Scripts have execution rights for the user executing them.
#! /usr/bin/bash
echo "Hello World"
Edit the file hello_world.sh using a text editor of your choice
and add the above lines in it.
Provide execution rights to your user.
Modify the file permissions and allow execution of the script
by using the command below:
OPERATOR USAGE
+ addition
- subtraction
* multiplication
/ division
** exponentiation
% modulus
Let's run a few examples.
#!/bin/bash
var=$((3+9))
echo $var
var=$((a+b))
echo $var
read x
read y
if [ $x -gt $y ]
then
echo X is greater than Y
elif [ $x -lt $y ]
then
echo X is less than Y
elif [ $x -eq $y ]
then
echo X is equal to Y
fi
Output:
if [ $a == $b -a $b == $c -a $a == $c ]
then
echo EQUILATERAL
elif [ $a == $b -o $b == $c -o $a == $c ]
then
echo ISOSCELES
else
echo SCALENE
fi
Output:
Test case #1
Test case #2
Test case #3
#!/bin/bash
for i in {1..5}
do
echo $i
done
#!/bin/bash
Reading files
Suppose we have a file sample_file.txt as shown below:
We can read the file line by line and print the output on the
screen.
#!/bin/bash
LINE=1
Syntax:
var= ` commands `
Example: Suppose we want to get the output of a list of
mountpoints with tmpfs in their name. We can craft a
statement like this: df -h | grep tmpfs.
To include it in the bash script, we can enclose it in back
ticks.
#!/bin/bash
for x in $@
do
echo "Entered arg is $x"
done
Run it like this:
./script arg1 arg2
How to Automate Scripts by Scheduling via cron
Jobs
Cron is a job scheduling utility present in Unix like systems.
You can schedule jobs to execute daily, weekly, monthly or in
a specific time of the day. Automation in Linux heavily relies
on cron jobs.