PAGE 1 – Shell Script Structure, Functions & Arguments
Shebang
#!/bin/sh
What it is:
Shebang tells the OS which shell should execute the script.
What it does:
Runs the script using /bin/sh.
Function Definition
myfunc()
{
echo "I was called as: $@"
x=2
}
What it is:
A function is a reusable block of code.
What it does:
• $@ → all arguments passed to the function
• x=2 → local assignment (overwrites global if not declared local)
Main Script
echo "Script was called with $@"
x=1
echo "x is $x"
myfunc 1 2 3
echo "x is $x"
Explanation:
• $@ → arguments passed to the script
• myfunc 1 2 3 → calls function with parameters
• Variable x changes from 1 to 2 because shell variables are global by default
Output
Script was called with
x is 1
I was called as: 1 2 3
x is 2
PAGE 2 – Arithmetic Using expr
Addition
expr 12 + 8
Output:
20
Division
expr 12 / 0
Output:
expr: division by zero
Zero Division Result
expr 0 / 1000
Output:
0
Variable Comparison
x=10
y=20
res=`expr $x = $y`
echo $res
What it does:
• = compares values
• Returns:
• 1 → true
• 0 → false
Output
0
PAGE 3 – String Length & Substring
String Length
x=ibees
len=`expr length $x`
echo $len
Output
5
What it does:
expr length returns number of characters.
Substring Extraction
x=ibees
sub=`expr substr $x 2 3`
echo $sub
Meaning:
• Start at position 2
• Extract 3 characters
Output
bee
Matching Strings
expr geeks : geek
Output
4
What it does:
Counts matching characters from the start.
PAGE 4 – Bash Arrays (Basics)
Array Declaration
#!/bin/bash
arr=(1 2 3 4 5)
What it is:
A static array in Bash.
Access Elements
echo ${arr[0]}
echo ${arr[1]}
Output
1
2
Loop Through Array
i=0
while [ $i -lt ${#arr[@]} ]
do
echo ${arr[$i]}
i=`expr $i + 1`
done
Explanation:
• ${#arr[@]} → array length
• Prints all elements
PAGE 5 – Array Indexing & Ranges
String Array
arr=(prakhar ankit shweta rishabh manish abhinav)
Indexing:
0 1 2 3 4 5
Print Elements
echo ${arr[@]}
echo ${arr[*]}
Prints all elements
Print From Index
echo ${arr[@]:1}
Prints elements from index 1 onwards
Print Range
echo ${arr[@]:2:3}
Meaning:
• Start index = 2
• Count = 3
Output
shweta rishabh manish
PAGE 6 – Array Size & Substitution
Array Size
echo ${#arr[@]}
echo ${#arr[*]}
Output
6
Substring Replacement
echo ${arr[0]//a/A}
What it does:
Replaces all a with A in element 0.
echo ${arr[0]//r/R}
Replaces all r with R.
KEY EXAM SUMMARY (VERY IMPORTANT)
Special Variables
Variable Meaning
$@ All arguments
$# Number of arguments
$0 Script name
$1 First argument
Arithmetic
expr a + b
expr a \* b
expr a / b
Array Syntax
arr=(a b c)
${arr[0]}
${arr[@]}
${#arr[@]}
${arr[@]:start:length}
Shebang Types
#!/bin/sh
#!/bin/bash
Function
• Functions are used to perform same task with different data.
• We can call a function anytime when required.
• It saves memory by reducing the redundancy in code.
• A function should always be declared before it is called in our program.
Syntax
function_name()
{
set of commands
....
}
• function_name is name of your function.
• Opening curly bracket after function name depicts start of the function definition.
• Set of commands is your code which will execute when function is called.
• Closing curly bracket depicts the end of the function body.
Return statement
Syntax
return [value]
• Return statement causes a function to terminate.
• It returns value if specified to caller, otherwise return value of last executed command is
returned.
Example 1
Let’s write a function which will print current date and time.
#!/bin/bash/
mydate()
{
echo "Today is :"
date
}
echo "Hello there"
mydate
echo "Have a nice day !"
Output
Hello there
Today is :
Tue 28 April 2020 19:50:34 IST
Have a nice day !
Example 2
Let’s write a function which takes parameters.
#!/bin/bash/
hello()
{
echo "Hello $1"
echo "Have a nice day !"
}
hello "Alisha"
Output
Hello Alisha
Have a nice day !
Explanation:
We have passed "Alisha" after we call function hello. "Alisha" is passed as parameter to hello function.
This parameter is stored in local variable $1.
Example 3
#!/bin/bash/
hello()
{
echo "Hello $1"
echo "Enjoy your stay in $2"
}
echo "What's your name?"
read name
read -p "Where are you from?" city
hello $name $city
Output
What's your name?
Alisha
Where are you from?
Pune
Hello Alisha
Enjoy your stay in Pune
Explanation:
The values passed to function hello are stored sequentially in local variables i.e. "Alisha" is stored in
$1 and "Pune" is stored in $2.
Example 4
Function that returns some value and prints it.
#!/bin/bash/
add()
{
sum=$(($1+$2))
return $sum
}
echo "Enter your marks for subject1"
read m1
read -p "Enter your marks for subject2?" m2
add $m1 $m2
echo "Your total marks are : " $?
Output
Enter your marks for subject1
75
Enter your marks for subject2
70
Your total marks are : 145
Comments
• A line starting with # is a comment line. Please consider that #! is shebang character and not a
comment.
• This line is ignored by the program.
• This line is descriptive text of code/function or anything that follows it.
• This is used by programmer to achieve readability.
__________________________________________________________________________________
1⃣ Simple if Statement
Syntax
if [ condition ]
then
commands
fi
Example
#!/bin/bash
echo "Enter a number:"
read n
if [ $n -gt 10 ]
then
echo "Number is greater than 10"
fi
Explanation
• -gt → greater than
• Condition is checked
• If true → commands inside then run
Output
Enter a number:
15
Number is greater than 10
2⃣ if – else Statement
Syntax
if [ condition ]
then
commands
else
commands
fi
Example
#!/bin/bash
echo "Enter your age:"
read age
if [ $age -ge 18 ]
then
echo "You are eligible to vote"
else
echo "You are not eligible to vote"
fi
Explanation
• -ge → greater than or equal to
• One block always executes
Output
Enter your age:
16
You are not eligible to vote
3⃣ if – elif – else Statement
Syntax
if [ condition1 ]
then
commands
elif [ condition2 ]
then
commands
else
commands
fi
Example
#!/bin/bash
echo "Enter marks:"
read marks
if [ $marks -ge 75 ]
then
echo "Distinction"
elif [ $marks -ge 60 ]
then
echo "First Class"
elif [ $marks -ge 40 ]
then
echo "Pass"
else
echo "Fail"
fi
Explanation
• Conditions are checked top to bottom
• First true condition executes
Output
Enter marks:
65
First Class
4⃣ Nested if Statement
Meaning
An if inside another if.
Example
#!/bin/bash
echo "Enter username:"
read user
echo "Enter password:"
read pass
if [ "$user" = "admin" ]
then
if [ "$pass" = "1234" ]
then
echo "Login successful"
else
echo "Wrong password"
fi
else
echo "Invalid user"
fi
Explanation
• Outer if checks username
• Inner if checks password
Output
Enter username:
admin
Enter password:
1234
Login successful
5⃣ String Comparison in if
if [ "$name" = "Alisha" ]
then
echo "Welcome Alisha"
fi
Operators:
Operator Meaning
= Equal
!= Not equal
-z String is empty
-n String is not empty
6⃣ Numeric Operators (VERY IMPORTANT)
Operator Meaning
-eq Equal
-ne Not equal
-gt Greater than
-lt Less than
-ge Greater or equal
-le Less or equal
7⃣ Logical Operators
if [ $a -gt 10 ] && [ $b -lt 20 ]
then
echo "Both conditions true"
fi
Operator Meaning
&& AND
NO
! NOT
Loops
Loops are very powerful programming tool, they allow users to perform task repetitively until certain
condition is met.
We will look at three loops:
• For loop
• While loop
• Until loop
1. For Loop
The loop is iterated through the set of values until list is exhausted or certain condition check
performed inside loop is met. The variable is set to every value given in the list.
Syntax
for variable in list
do
statement
..
done
Example 1
#!/bin/bash
for i in {1,"computer",-5,"hello"}
do
echo "hello this is value: $i"
done
Output
hello this is value: 1
hello this is value: computer
hello this is value: -5
hello this is value: hello
As you can see for every value of i in list the set of instructions in loop is repeated.
And after every interaction i is set to next value in the list.
Example 2
for i in {1,"computer",-5,"hello"}
do
echo "hello this is value: $i"
if [ i == -5 ]
echo "Terminate"
break
done
Output
hello this is value: 1
hello this is value: computer
hello this is value: -5
As you can see when the value of i becomes -5 if condition is satisfied and the for loop is terminated.
2. While Loop
While loop is executed until certain condition is met.
Syntax
while [ Condition ]
do
statement
..
done
Example 3
number=3
while [ $number -le 15 ]
do
echo "number is $number"
number=$(( number +3 ))
done
Output
number is 3
number is 6
number is 9
number is 12
As you can see the loop is executed until number becomes 15.
3. Until Loop
The loop continues until the condition evaluates to be true.
Syntax
until [ condition ]
do
statement
..
done
Example 4
i=1
until [ $i -gt 3 ]
do
echo "Hello there: $i"
i=$((i+1))
done
Output
Hello there: 1
Hello there: 2
Hello there: 3
4. Break Statement
The break statement is used to terminate the loop. Consider example 2, here for loop variable i is
iterated through certain set of values. When i becomes -5 the loop is terminated through the break
statement that is loop is not iterated for the remaining values in the list.
5. Continue Statement
The continue statement when used in loop it skips the commands below it and jumps to next iteration
of loop.
Example 5
for i in {1,2,3,4}
do
if [ i == 2 ]
continue
echo "hello this is value: $i"
done
Output
hello this is value: 1
hello this is value: 3
hello this is value: 4
Variables
• Variables are useful to store data and perform various operations on it later in the program.
• In shell scripting we have two types of variables.
1. System Variables
• These variables are created and maintained by operating system itself.
• Generally these variables are all in capital letters.
• We check values of these environment variables using echo command.
Example:
echo $PATH
To see all the environmental variables set by operating system we just type set or env in command
prompt.
Following are some system defined variables with there meaning:
1. PATH = The search path in which shell will look for commands.
2. HOME = Path for current users home folder
3. USER = The current user name
4. UID = Current user's unique id.
5. SHELL = Path of the shell being used by user.
6. TERM = Type of the terminal for user
7. HOSTNAME = Name of your computer
8. EDITOR = Path of the program which will be used to edit your content.
• To set any system variable;
export variable=value
• There are certain variables which are already set for programmer.
Example 1
#!/bin/bash/
hello()
{
echo "Hello $1"
echo "Have a nice day !"
}
hello "Alisha"
Output
Hello Alisha
Have a nice day!
Variables $0 to $9 and $# are set by shell.
$0 is the program name.
$# is for the number of parameters and $1 to $9 saves the parameters passed.
• $? this variable is set by shell to store the return value or exit value of last run command.
• $! this variable is set by shell which stores PID of the last run background process.
• $$ this variable is set by shell which stores the PID of currently running shell.
2. User Defined Variables
Syntax
variable_name=value
• Unlike other programming languages while declaring variable programmer need not mention
data type. It automatically determines the data type.
• There should not be any space on either side of assignment operator (=).
• To access a variable one must use $ before variable name.
Example 2
#!/bin/bash/
myvar=Alisha
echo "Hello $myvar"
Output
Hello Alisha
Example 3
#!/bin/bash/
echo "Hello $myvar"
myvar="Alisha"
echo "Hello $myvar"
Output
Hello
Hello Alisha
Explanation:
Here as we can in the first line of program we are trying to access the variable myvar which is
declared later in the program. So basically this variable has not come into scope yet hence not
accessible.
To make above program work we can export a script variable before it is executed as follows:
Let’s name the program as [Link].
export myvar="Monisha"
./[Link]
Output
Hello Monisha
Hello Alisha
-> The value of myvar is changed in program at line 3.
Note: We can also execute shell script using ./shell_script
Example 4
#!/bin/bash/
echo "Hello,enter your amount"
read amount
echo "Your total balance is: $(amount +200)"
Output
Hello,enter your amount
1200
Your total balance is: 1400
-> To unset a variable that is to delete a variable we can use unset command. Once a variable is unset
it can not be accessed.
Example 5
#!/bin/bash/
myvar=100
echo "Amount is: $myvar"
unset myvar
echo $myvar
Output
Amount is: 100
Arguments In Shell Scripting
-> We can pass command line arguments to shell script.
-> As we have learnt in variables chapter that –
• Variable $0 is used by shell to store the script name.
• Variables $1 to $9 are for arguments passed to shell script.
• $* represents all the arguments.
• $@ represents all arguments but in separated form.
Example 1
[Link]
#!/bin/bash/
echo "Hello : $1"
Execute:
./[Link] Alisha
Output
Hello Alisha
Example 2
[Link]
if [ $1 -le 0 ]
then
echo "You seem to have entered wrong value"
echo "Age can not be negative"
exit
fi
echo "Welcome to shell programming! Lets get started"
Execute:
./[Link] -5
Output
You seem to have entered wrong value
Age can not be negative
Explanation:
The age entered here is less than 0, so it enters into if loop and program
terminates due to exit statement.
Note
-> In shell programming we use
• -le to check if a variable is less than some value.
• -gt to check if a variable is greater than some value.
• -eq to check if two variables are equal.
One can use comparison operator as well, just ensure space on either side of
comparison operator same as we give space after brackets in condition check
statement i.e after [ ].
Exit Command
-> We can see that once the control has entered inside if statement the program
terminates its execution there itself. The echo statement after if statement is not
printed on terminal because we have exit command in if statement.
-> Exit command is used to terminate the shell script.
Syntax
exit N
-> Every command executed has a return value. If value returned is zero then it
means successful execution, any non-zero value tells unsuccessful execution of the
command.
-> Value N can be given by programmer, if not provided it takes the value of last
executed statement.
-> This value can be utilized by other commands or script itself.
-> We can use $? variable to check the exit value.
-> The range of exit codes is 0 to 255. Zero is traditionally used to represent
success, every other value has meaning.
Example 3
Execute:
pwd -adsfff
echo $?
-> The parameter given to pwd command is invalid, hence the command can not be
executed successfully.
-> To print the exit status of pwd -adsfff command we can echo $? variable.
We will now see some basic commands in this chapter.
Syntax of any unix command:
command (-option) (data)
It is not mandatory to provide option and data for every command.
Following are some of the basic commands –
1. date:
This command prints date and current time.
ex.
date -u
This will print date and current time in universal format (UTC).
2. killall:
syntax :-
killall ProcessName
This command terminates the process mentioned in command.
3. cal:
This command will print calender of the user given month and year.
Syntax :-
cal month and year
Example1:
cal 01 2010
Output: Gets calender of year 2010 and month january.
Example2:
cal
Output: This will print calender of current month and year.
4. whoami:
This command tells which user we have logged in as.
5. pwd:
This tells in which directory user is currently working in.
6. ls:
This command will list down the contents of current directory.
Example1:
ls
Output: Lists content of current directory.
Example2:
ls -a Desktop/
Output: With the use of -a in the command we can also see the hidden files along
with the other files in the directory named Desktop.
Example3:
ls -l
Output: This command gives us name, last edited/created, size of file, group to
which it is assigned.
drwxr-xr-x or -rwxr-xr-x -> File Permissions
The first character d or - says it is a file or directory. The subsequent
characters are grouped in three characters per group.
• rwx = The first group belongs to owner. Owner has read, write and execute.
• r-x = The second group belongs to group. Group has read and execute.
• r-x = The third group belongs to others. Others has read and execute.
7. file:
To get information of a particular file that is what type of text it contains we
can use file command.
Ex.
file [Link]
8. touch:
Using this command we can create file, modify and update the timestamp of the file.
Ex.
touch [Link]
9. mkdir:
syntax:-
mkdir newfolder
To make a new directory/folder.
10. mv:
This command is used to move files or renames files and directories.
Example1:
mv [Link] [Link]
This will rename file [Link] to [Link]
Example2:
mv [Link] foldername
This will move [Link] to foldername
11. sudo:
-> sudo command lets you act as a root user. A root user is a super user which
allows you to do anything.
-> To avoid typing sudo everytime in command prompt, we can type sudo bash.
This will open terminal in root session.
-> To exit from root session we can give exit command.
12. chown:
This command is used to change the owner of file. In order to change user one must
be super user.
Ex.
sudo chown user1 [Link]
File [Link]’s owner is changed to user1.
13. chgrp:
This command is used to change the group of a file. In order to change group one
must be group.
Ex.
sudo chgrp guest [Link]
File [Link]’s group is changed to guest.
14. chmod:
This command is used to change the permissions. The previous permissions are
overwritten by new permissions i.e if a file ([Link]) has permissions as -r-x and
chmod u=rw [Link]
then new permissions will be -rw-.
Here u is owner, g is guest and o is others group.
Example1:
chmod -x [Link]
Now the file [Link] will not be executable by any group (owner,guest,other).
Example2:
chmod +x [Link]
Now the file [Link] will be executable by any group.
15. * sign:
* means zero or more characters.
Example1:
file a*
All the files starting with a will be listed.
Example2:
mv *.txt foldername/f1
All the files with extension .txt are moved to foldername/f1
Example3:
mv A-folder/*.png .
All the png files are moved to current directory. Dot (.) represents current
directory.
16. echo:
Example1:
echo "Hello there"
This command will print string "Hello there".
17. tail:
This command is used to read only last few lines of a file.
Ex.
tail -4 [Link]
Only last 4 lines of file [Link] are displayed.
18. sort:
Sorts the contents of the file.
Ex.
sort > [Link]
This sorts the file [Link]
19. clear:
This command is used to clear the terminal. So all the commands and its output
given before typing in clear command will wiped out.
20. open:
This command will open the input data in understandable application. It will first
look for a program which will understand the given input type.
Ex.
open [Link]
It will open [Link] file in a text editor.
21. which:
This command tells you the path.
Example1:
which ls
output:
/bin/ls
This will tell you the full path of the command ls.
22. cd:
This command is used to change the directory name.
Example1:
cd Desktop/
Terminal will go to Desktop directory name.
Example2:
cd ..
This will move one level up in current directory. ie suppose user is in
cd /bin/bash/ls directory. On giving command cd .. we will go to /bin/bash
directory.
23. cp:
This command is used to copy files.
Example1:
cp [Link] [Link]
A file named [Link] is copied to file named [Link] in same folder.
24. rm:
This command is used to remove files and directories.
Example1:
rm [Link]
This will delete file [Link] from current directory.
Note:
1. To work with directories
cp A-folder/ B-folder/
In this way we can't copy contents of one folder to another folder.
rm A-folder/
A-folder has lot of files in it. So this command will throw error.
To make above two commands work we need to use -R option which means perform this
task recursively.
Correct Commands-
cp -R A-folder/ B-folder/
rm -R A-folder/
But while moving one folder contents to another we need not use -R.
-> Consider below folder structure for directory named-desktop.
(Desktop folder structure shown)
-> Lets run ls command on above folder structure considering that current directory
is Desktop.
ls
output
[Link] [Link] [Link]
script/ data/
-> Now lets use -R option in above command.
ls -R
output
[Link] [Link] [Link]
script/ data/
./script:
[Link] [Link]
./data:
[Link]
As you can see not just this lists file and directories in desktop, but it also
lists down the contents inside directories script and data.
25. Redirect output to a file:
-> echo command will print string passed to this command on terminal. If user wants
to save it into file it can be done
find foldername -type file