BASH script tutorial- write your own terminal commands

LINUX is a kernel written by Linus Torvalds which is based on UNIX.

Linux Distributions: UBUNTU, DEBIAN etc.

What is Kernel?

It

-provides access to “Computer Hardware”

-provides control access to resources like files, data, memory etc

-decides who can use resources and for how long and when?

-some of its tasks are memory management, process management, file management, device drivers etc

What is SHELL?

It is a program for user interaction. Shell is a mediator between user commands and Kernel.

Diagram:

shell

Some examples of shells are

  • BASH (Bourne-Again SHell)
  • CSH (C SHell)
  • KSH
  • TCSH , etc

What is operating system?

OS = Kernel + Shell + GUI+ tools +services

Block Diagram:

 os

What is SHELL SCRIPT?

It is a file containing series of commands

Why SHELL SCRIPT?

  • One can create his own terminal commands (applications)
  • Re-usability or automating processes
  • Customize Linux administrator tasks
  • Ex: Data Backup, search for a file containing particular words in the system etc

BASH SHELL:

It supports 2 types of commands

  1. Internal Commands (part of the shell)
  2. External Commands (user/bin,user/local/bin etc)

To know whether a command is internal or external use following command use type -a command

To know the shells present in your system use cat /etc/shells

Output:/bin/sh

/bin/dash

/bin/bash

/bin/rbash etc

Introduction to BASH SHELL SCRIPT: Like we mention header files in c/c++, we have to mention the path to bash interpreter using shebang (#!), So BASH Script starts with

#! /bin/bash

Executing BASH SCRIPT:  Save file with an extension .sh & then execute using

./filename.sh 

Permission denied right? check the permissions by ls -la command

if user has no permission to execute then run chmod +x filename.sh , then ./filename.sh 

Debugging BASH SCRIPT: There are 3 ways to debug,

  1. while executing: bash -x filename.sh
  2. change shebang to #! /bin/bash -x in your program
  3. for some lines of code in your program : set -x
#! /bin/bash
echo "first command"
#start debug mode
set-x
echo "second command"
echo "third command"
#stop debug mode
set +x

Conditional Statements: There are 2 ways of writing if condition

if [ condition ]
 then
 command1
 command2
 .
 .
 commandn
else
 command1
 .
 commandn
fi

(or)

if test condition
then
       command1
       command2
        .
        .
       commandn
else
    command1
    .
    commandn
fi

* test or [ expr ] in if condition only works with integers (not for float), strings,files

*there should be a space between square brackets and the condition, otherwise it will through you an error 

*To get float division we have to use bc or basic calculator or bench calculator

Ex: echo “scale=10; 22/7” | bc

Arithmetic comparisons: Generally in high level languages we use <,<=,>,>=,== operators, but in BASH SCRIPT we have to use -lt, -le, -gt, -ge, -eq respectively.

for example: suppose you want to perform 3 == 6, which we can do like the following if test 3 -eq 6 or if [ 3 -eq 6 ]

String comparisons: For string comparisons we use ==,<,<=,>,>=

suppose s1 and s2 sre strings

s1==s2             are s1 and s2 equal?

s1!=s2              are s1 and s2 not equal?

-n s1                 s1 not null and s1 exixts

-z s1                  s1 null and s1 exists

s1                      s1 not null or s1 not defined

File comparisons:

-r  file_name                     is file readable?

-w   file_name                   is file writable?

-x file_name                     is file executable?

-s file_name                      is file nonempty?

-d directory_name           is directory exists and it is not a file?

Logical Operators:

Logical NOT             ! expression

Logical AND             exp1 -a exp2

Logical OR                exp1 -o exp2

Loop Control:

The For Loop:

for ((i=0;i<=$n;i++))
do
   #commands here
done

(or)

for i in ${some_array[@]}
do
   #commands here
done

The While Loop:

while [ condition ]
do
   #commands
done

*there should be a space between square brackets and the condition, otherwise it will through you an error
Switch case:

case $var_name in
pattern1) commands
pattern2) commands
.
.
esac

Functions:

function_name ()
{ input_argument_1=$1
  input_argument_2=$2
  .
  .
  commands
}

Calling a function:

function_name

or

function_name ()

or

function_name value_1 value_2 value_3…


Following program will help you to understand the basic syntax of bash script:

#! /bin/bash
#clear the terminal first
clear
#print system variable $USER or $HOSTNAME
echo "Hello $USER"
#\c print who in the currentline only, to use \c mention -e after echo
echo -e "i am \c";who
echo -e "hi \c "
pwd
read -p "press enter key to continue"
printf "hi this is $USER \n"

#create a new variable (user variable)
new_var=hyderabad
echo "$new_var"
files=$(ls -l)
echo "${files}"

#defualt value:if there is no previous values exists then the defaut value will be considered
echo "$files:=no_previois_value"
unset files
echo "$files:=no_previous_value"

#sleep for 3 secs
sleep 3

<<comment
take 2 no's from the user using standard input and calculate
the sum of two numbers
comment

read -p "enter two numbers" var1 var2
sum=$((var1+var2))
printf "sum value is $sum\n"

#declare an integer variable
declare -i count=10

#declare a constant variable
declare -r const_var=12

#create an array
declare -a new_array1

# or

new_array2=('United States' India Japan)
echo $new_array2[*]
echo ${new_array2[*]}
echo ${new_array2[2]}

#add new element to new_array2
new_array2[3]=China

#deleting array elements
unset new_array2[0]
echo ${new_array2[*]}

#use of conditional statements
#arithmatic comparisions
<<c1
here test is a command to perform string comparisons and arithmetic
comparisons
c1

value=10
if test $value -ge 20
 then
 echo "value is greater than 20"
else
 echo "value is less than 20"
fi

#we can replace the test by square brackets []
if [ "$value" -ge "20" ]
then
 echo "value is greater than 20"
else
 echo "value is less than 20"
fi

#iterate through the array-for loop
#get the size of the new_array2
size=${#new_array2[@]}

for ((i=0;i<=$size;i++))
do
 echo "${new_array2[i]}"
done

# or

for i in ${new_array2[@]}
do
 echo "$i"
done 

#while loop
j=0
while [ $j -le $size ]
do
 echo "${new_array2[j]}"
 j=$[$j+1]
done

#functions
sub(){
i1=$1
i2=$2
echo "$i1"
echo "$i2"
echo "$[$i1 - $i2]"
}

#call the function sub by passing two arguments
sub 5 4
exit 0

Leave a comment