0% found this document useful (0 votes)
2 views16 pages

2 IT628 Systems Programming-Shell Scripting, Jan 5

The document provides an overview of shell scripting, detailing types of shells, shell scripts, variables, operators, control statements, loops, input/output redirection, and functions. It includes examples of syntax and usage for each topic, such as defining variables, using conditional statements, and creating functions. Additionally, it presents exercises for practicing shell scripting skills.

Uploaded by

Raj Savaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

2 IT628 Systems Programming-Shell Scripting, Jan 5

The document provides an overview of shell scripting, detailing types of shells, shell scripts, variables, operators, control statements, loops, input/output redirection, and functions. It includes examples of syntax and usage for each topic, such as defining variables, using conditional statements, and creating functions. Additionally, it presents exercises for practicing shell scripting skills.

Uploaded by

Raj Savaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

IT628 Systems Programming

Shell Scripting
Types of Shell
• Bourne Shell – with $ as default prompt
• Bourne Shell (sh)
• Korn Shell (ksh)
• Bourne Again Shell (bash)
• POSIX Shell (sh)
• C-type Shell – with % as default prompt
• C Shell (csh)
• TENEX/TOPS C Shell (tcsh)
Shell Scripts
• All shell scripts has extension .sh (e.g. test.sh)
• Use shebang (#!) to indicate which shell you are using for shell script e.g.
test.sh will contain
#!/bin/bash
pwd
ls
• Use # for comments
#!/bin/bash
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:
Variables
• Shell Variables
• Environment Variables
• SHELL=/bin/bash
• PATH=/usr/bin/
• USER=“logged in user”
• HOME=“path to home folder”
• Many others…
• Local Variables
• Any variable that is defined in shell script by developer e.g. AUTHOR=“Amit”
• Access variables using $ sign e.g. echo $PATH will display the value stored in
environment variable PATH
Special Variables
• $$ - process id (PID) of current shell • echo command is used to print value of any
constant or variable
• $0 - shell script filename being e.g. test.sh has been created with these two lines
executed #!/bin/bash
• $1, $2, $3…$n – command line echo “File name: $0”
argument echo “First command line argument is: $1”
• $# - number of command line echo “Second command line argument is: $2”
argument Now run: tesh.sh abc xyz
• $? – exit status of last command Output will be:
executed (generally 0 means File name: test.sh
success, 1 means error) First command line argument is: abc
• $! – PID of last background Second command line argument is: xyz
command
Arrays

Definition Accessing
NAME[0]=“Deepak“ • To display value from a specific
index
NAME[1]=“Renuka”
echo "First Index: ${NAME[0]}"
NAME[2]=“Joe“ echo "Second Index: ${NAME[1]}“
NAME[3]=“Alex“ • To display all values
NAME[4]=“Amir“ echo "First Index: ${NAME[*]}“
Or in bash OR
array_name = (value1 ... valuen) echo "First Index: ${NAME[@]}"
Operators
• Arithmetic Operators: + - * / % = == !=
• c=`expr $a + $b` add values from a and b and assign it to c
• a=$b would assign value of b into a
• [ $a == $b ] OR [ $a != $b ] would compare numeric values of a and b
• Relational Operators: -eq –ne –gt –lt –ge –le
• Works for string variables also
• Boolean/Logical Operators: ! –o –a
• String Operators: = != -z –n str
• = (or !=) checks returns true if strings are equal (or not equal) respectively
• -z (or -n) returns true if string length is zero (or non-zero)
• str returns true if string is not empty
Operators
• File Test Operators (assuming file #!/bin/bash
variable holds the filename) testfile=test.sh
• -d file: true if file is a directory
• -f file: true if ordinary file instead
If [ -e $testfile ]
of directory or special file then
• -r file: true if file is readable echo “file exists”
• -w file: true if file is writable
• -x file: true if file is executable else
• -s file: true if file size > 0 echo “file does not exists”
• -e file: true if file exists fi
Decision Making Conditional Statments
• If…fi statement case word in
• If…else…fi statement pattern1)
• If…elif…else…fi statement Statement(s) to be executed if
pattern1 matches ;;
pattern2)
Statement(s) to be executed if
pattern2 matches ;;
pattern3)
Statement(s) to be executed if
pattern3 matches ;;
*)
Default condition to be
executed ;;
esac
Loops – Nested Loops are Allowed
• While Loop: • Until Loop:
while command until command
do do
Statement(s) to be executed if Statement(s) to be executed
command is true until command is true
done Done
• For Loop: • Select Loop (Used for creating Menu):
for var in word1 word2 ... wordN select var in word1 word2 ... wordN
do do
Statement(s) to be executed for Statement(s) to be executed for
every word. every word.
done done
Loop Control Statements
• break statement • continue statement
#!/bin/sh a=0 #!/bin/sh
while [ $a -lt 10 ] NUMS="1 2 3 4 5 6 7"
do for NUM in $NUMS
echo $a do
if [ $a -eq 5 ] Q=`expr $NUM % 2`
then if [ $Q -eq 0 ]
break then
fi echo "Number is an even
number!!"
a=`expr $a + 1`
continue
done
fi
echo "Found odd number"
done
Substitution
• Escape sequences with echo • Command Substitution using
command `command`
• \\ (backslash) DATE=`date`
• \b (backspace)
• \c (suppress trailing newline) echo "Date is $DATE"
• \f (form feed) USERS=`who | wc -l`
• \n (new line) echo "Logged in user are $USERS“
• \r (carriage return)
• \t (horizontal tab) • Variable Substitution
• \v (vertical tab) ${var}
• For echo command, use -e (-E) ${var:-word}
option to enable (disable)
interpretation of backslash escapes ${var:=word}
${var:?message}
Input and Output Redirection
• Command/Program > file
• Any output from command or program execution will be saved in file instead of displaying to
STDOUT
• New file will be created if does not exist or existing file will be erased first
• Command/Program >> file :
• Any output from command or program execution will be appended to an existing file instead of
displaying to STDOUT
• New file will be created if does not exist but if file already exists then it is appended
• n >> file : output from stream with descriptor n is appended to a file
• n >& m : merges output from stream n with stream m
• Command/Program < file : Input to the command or program is fed from data in file
• n <& m : merges input from stream n with stream m
• | (called pipe) : Takes output from one process and feed into another process
Functions
Parameter Passing and Returning
Create Function Values
#!/bin/sh #!/bin/sh
# Define your function here # Define your function here
Hello () { Hello () {
echo "Hello World" echo "Hello World $1 $2"
} return 10
}
# Invoke your function
# Invoke your function
Hello
Hello Zara Ali
Note: Nested functions and recursive functions
are allowed # Capture value returnd by last command
Functions can be accessed in shell prompt by ret=$?
placing them in .sh file and executing that .sh echo "Return value is $ret"
file in a shell prompt
Exercises
• Print sum of all command line integer arguments

• Print the factorial of a given number using fact() function

• Print the day of the week for all the command line values provided
between 1 and 7

• Given path (e.g. /usr/local/lib or /etc/passwd), first check if that path


exists and then check if it is a file or a directory and print appropriate
message
Print sum of all command line arguments
#!/bin/bash
echo $#
i=1
sum=0
while [ $i –le $# ]
do
sum=`expr $sum + $i`
i=‘expr $i + 1`
done
echo $sum

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy