Search This Blog

Saturday, 20 February 2021

Basic Shell scripting for beginners

 What is a Shell ?

shell is a command line interpreter. It is an interface between user and the kernel. It takes commands from the user and executes them. 

There are different types of shells available in Linux. 

Shell

Developed By

Path

Default Prompt

Bourne (sh)

Stephen Bourne  

/bin/sh and sbin/sh

$

Korn (ksh)

David Korn

/bin/ksh

$

Cshell (csh)

Bill Joy

/bin/csh

%

Bash (sh/bsh)

Brain Fox

/bin/bash

$

Zsh (zsh)

Paul Falstad

/bin/zsh

$


Shell Variable types:

  1. Unix Defined or System Defined Variables
  2. User Defined Variables

1) Unix Defined Variables: These are stranded variable which are always accessible. The shell provide the values for these variables. These variables are usually used by the system we can change the variables as per over preference an customize the system environment.

Few system defined variables

[root@linuxhost ~]# set | grep ^HOME
HOME=/root
[root@linuxhost ~]# set | grep ^LOGNAME
LOGNAME=root
[root@linuxhost ~]# set | grep ^SHELL
SHELL=/bin/bash
SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
[root@linuxhost ~]# set | grep ^MAIL
MAIL=/var/spool/mail/root
MAILCHECK=60

PS1=$primary shell prompt
Ps2= > -system prompt(default values)
SHELL=/bin/sh
TERM=vt100
TZ=ist-5:30
PATH:- Define the which shell  must search in order to command .
HOME:-Store the default working directory of the user.
LOGNAME:-Store the log name of the user.
MAIL:-Define the file where the mail of user stored.
IFS:-Define the internal felid separator which is space or tab or newline
SHELL:-Define the name of  the your  working shell.
TERM:-Define the name of the terminal which you are working.
TZ:-Define the name of the time zone in which you are working.

2) User Defined Variables: These are defined by the user and used most exclusively  in shell programming.

Rules for creating shell variables:

The first character should be alphabet or Underscore ( _ )
  • Eg:- -a= ,a=,b=,c=,d=
No commas or blanks are allowed
  • Eg:-a,b=10 is worng
Variable names should be case sensitive
  • Eg:-name=,Name=,nAme=
Variable names should not be a shell keyword.
  • Key words are words which meaning as already been explained to the shell.
  • Keywords are also called as reverse words
  • The list of key words are in bourn shell: echo for if untill read else case set wait fi esas unset eval while readonly break do shift exec continue done ulimit export exit umask return frap
echo statements: echo command is used to display the message on the screen and it is used to display the values stored in a shell variable.

Example:
[osboxes@linuxhost ~]$ echo "welcome"
welcome

Unix command should be in backquote/backtick ( ` ) in echo statement, otherwise it treats as a text

Examples:

[osboxes@linuxhost ~]$ echo "Today's date is : date"
Today's date is : date

[osboxes@linuxhost ~]$ echo "Today's date is : `date`"
Today's date is : Sun Feb 14 08:11:15 EST 2021

[osboxes@linuxhost ~]$ echo "Present working directory is : `pwd`"
Present working directory is : /home/osboxes

Shell variables/User defined Variables:

[osboxes@linuxhost ~]$ a=10
[osboxes@linuxhost ~]$ b=20
[osboxes@linuxhost ~]$ name="pavan"

[osboxes@linuxhost ~]$ echo $a
10
[osboxes@linuxhost ~]$ echo $b
20
[osboxes@linuxhost ~]$ echo $name
pavan

Null Variables: A variable which is defined but not assigned any value is known as a null variable.

[osboxes@linuxhost ~]$ d=""
[osboxes@linuxhost ~]$ echo $d

[osboxes@linuxhost ~]$ e=''

[osboxes@linuxhost ~]$ echo $e

Constant Variable: It is fixed value and doesn't change during the execution of the program. When the variable readonly the shell doesn't allow you to change their values.

[osboxes@linuxhost ~]$ b=14
[osboxes@linuxhost ~]$ readonly b
[osboxes@linuxhost ~]$ b=15
-bash: b: readonly variable

Unset: A variable and its value assigned to it are erased from shell memory.

[osboxes@linuxhost ~]$ c=30
[osboxes@linuxhost ~]$ echo $c
30
[osboxes@linuxhost ~]$ unset c
[osboxes@linuxhost ~]$ echo $c

[osboxes@linuxhost ~]$

Escape Sequences:

\n means newline
\r means return
\t means tab
\v means vertical tab
\b means backspace
\a means "alert" (beep or flash)
\0xx translates to the octal ASCII equivalent of 0xx

\”                 double quote                  
\’                 single quote
\\                 backslash     

Sample Program:
Write a program to display list of files and directories and present working directories and no of users logged into the system. You can execute the script in two ways (./sample.sh or sh sample.sh)

[osboxes@linuxhost ~]$ cat>sample.sh
#!/bin/bash
ls -l
pwd
who
[osboxes@linuxhost ~]$ chmod a+x sample.sh

[osboxes@linuxhost ~]$ ./sample.sh
total 4
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Desktop
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Documents
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Downloads
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Music
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Pictures
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Public
-rwxrwxr-x. 1 osboxes osboxes 26 Feb 14 08:33 sample.sh
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Templates
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Videos
/home/osboxes
osboxes  pts/0        2021-02-14 06:28 (192.168.1.5)

[osboxes@linuxhost ~]$ sh sample.sh
total 4
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Desktop
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Documents
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Downloads
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Music
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Pictures
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Public
-rwxrwxr-x. 1 osboxes osboxes 26 Feb 14 08:33 sample.sh
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Templates
drwxr-xr-x. 2 osboxes osboxes  6 Jul  4  2020 Videos
/home/osboxes
osboxes  pts/0        2021-02-14 06:28 (192.168.1.5)

Write a program to count no of users are currently logged into the system.

[osboxes@linuxhost ~]$ cat>numberofusers.sh
#!/bin/bash
echo "No of users logged into the system: `who |wc -l`"

[osboxes@linuxhost ~]$ sh numberofusers.sh
No of users logged into the system: 1

Write a program to accept the user input from the terminal. 
(Hint: read command reads value from the keyboard up to space or enter key)

[osboxes@linuxhost ~]$ cat>input.sh
#!/bin/bash
echo "Enter your name:"
read name
echo "Your Name is : $name"

[osboxes@linuxhost ~]$ sh input.sh
Enter your name:
pavan
Your Name is : pavan

Write a program to read two numbers and display.

[osboxes@linuxhost ~]$ cat>inputvalues.sh
#!/bin/bash
echo "Enter two values: a b"
read a b
echo "You have entered : $a $b "

[osboxes@linuxhost ~]$ sh inputvalues.sh
Enter two values: a b
2 3
You have entered : 2 3

Operators:

1) Arithmetic Operators
2) Relational Operators: 
    Numeric Comparison
    String Comparison
3) Logical Operators

1) Arithmetic Operators: Addition ( + ),  Subtraction ( - ), Multiplication ( * ), Division ( / ), Modulus Division ( % )
2) Relational Operators: -gt ( > ),  -ge ( >= ),  -le ( <= ),  -eq ( = ),  -ne ( != )
3) Logical Operators:
    And   -a
    Or     -o
    Nor   -!

Write a program to read two numbers and display sum diff product and division.
(Hint: expr is a command to evaluate arithmetic expressions. But expr is capable of carrying out only integer arithmetic.  Escape sequence ( "\"  is used for wild card characters  * , - , ? , [ , ] )

[osboxes@linuxhost ~]$ cat>operators.sh
#!/bin/bash
echo "Enter two values: a b "
read a b
c=`expr $a + $b`
echo " a and b addition is : $c "
c=`expr $a - $b`
echo " a and b subtraction is : $c "
c=`expr $a \* $b`
echo " a and b product is : $c "
c=`expr $a / $b`
echo " a and b division is : $c "

[osboxes@linuxhost ~]$ sh operators.sh
Enter two values: a b
4 2
 a and b addition is : 6
 a and b subtraction is : 2
 a and b product is : 8
 a and b division is : 2

If conditional statements:

if statement:

if condition
   then
   ---------
   ---------
   ---------
fi

if-else statement:

if condition
   then
   --------
   --------
   --------
else
   -------
   -------
   -------
fi

if-elif-else statement:

if condition
   then
   --------
   --------
   --------
elif condition
   then
   ----------
   ----------
   ----------
else
   ----------
   ----------
   ----------
fi


if 0  is true
if 1 is false

Write a program to change the directory.

[osboxes@linuxhost ~]$ cat >changedir.sh
#!/bin/bash
echo " Enter a directory name: "
read dir
if cd $dir
then
   echo " Change the directory to $dir "
   pwd
fi

[osboxes@linuxhost ~]$ sh changedir.sh
 Enter a directory name:
Desktop
 Change the directory to Desktop
/home/osboxes/Desktop

Write a program to copy a file

[osboxes@linuxhost ~]$ cat>filecopy.sh
#!/bin/bash
echo "Enter source and target: "
read source target
if cp $source $target
then
        echo " File copied from $source to $target "
else
        echo " File copy failed"
fi

[osboxes@linuxhost ~]$ sh filecopy.sh
Enter source and target:
sample.sh sample1.sh
 File copied from sample.sh to sample1.sh

Write a program to find greatest number of two numbers.

[osboxes@linuxhost ~]$ cat>gretestnumber.sh
#!/bin/bash
echo "Enter two numbers: "
read a b
if [ $a -gt $b ]
then
   echo " $a is the greatest number "
else
   echo " $b is the greatest number "
fi

[osboxes@linuxhost ~]$ sh gretestnumber.sh
Enter two numbers:
8 1
 8 is the greatest number

Write a program to check the given number is even or odd.

[osboxes@linuxhost ~]$ cat even-odd.sh
#!/bin/bash
echo "Enter a number: "
read num
if [ `expr $num % 2` -eq 0 ]
then
   echo "$num is even number"
else
   echo "$num is odd number"
fi

[osboxes@linuxhost ~]$ sh even-odd.sh
Enter a number:
8
8 is even number

test command:  the test command is used to perform checks and comparisons. 
Here's its syntax: test expression
test checks the file types and variables

if test condition
then
   commands
else
   commands
fi


Write a program to check how many users are working on the system.

[osboxes@linuxhost ~]$ cat noofusers.sh
#!/bin/bash
total=`who|wc -l`
if test $total -eq 1
then
        echo "you are the only user logged in"
else
        echo "total no of users logged in: $total"
fi

Write a program to check the given number is +ve or –ve?

[osboxes@linuxhost ~]$ sh noofusers.sh
you are the only user logged in

[osboxes@linuxhost ~]$ cat numbercheck.sh
#!/bin/bash
echo " enter a number "
read num
if test $num -gt 0
then
        echo " the number is +ve "
elif test $num -eq 0
then
        echo " the number is 0 "
else
        echo " the number is -ve "
fi

[osboxes@linuxhost ~]$ sh numbercheck.sh
 enter a number
-9
 the number is -ve
[osboxes@linuxhost ~]$








No comments: