Shell Scripting Part I
Shell Scripting Part I
What is Shell ?
• Unix Shells are the executables that provide the user-
interface to the user.
• Bourne Shell
• Korn Shell
• C Shell
syntax:
chmod permission your-script-name
Examples:
$ chmod +x your-script-name
$ chmod 755 your-script-name
Execute shell script
(3) Execute your script as
syntax:
bash your-script-name
sh your-script-name
./your-script-name
Examples:
$ bash bar
$ sh bar
$ ./bar
Shell Variables
User-created Shell Variables:
variable=value => assigns value to variable
$variable => refers value of the variable
To display a variable:
echo $var “$var” ‘$var’
the output:
hello hello $var
read statement:
To read a value in a variable form keyboard:
read var
Unix - Special Variables
Variable Description
$# The number of positional parameters.
$- Shell Options.
$? The exit status of the last executed command.
$$ The process number (PID) of the last executed
command.
$! The process number (PID) of the last background
command.
$0 The name of the command being executed.
$* List of positional parameters.
$@ Same as $* except when enclosed in double quotes
Shell Arithmetic Operators
expr command
This command is used to evaluates expressions. Use
to perform arithmetic operations.
Syntax:
expr op1 math-operator op2
e.g.
expr 10 + 20
Operators
Arithmetic:
+ Add
- Subtract
/ Divide
\* Multiply
% Modulo
Command Line Arguments
The most important concept in shell scripts is passing
arguments to a script.
Operator Description
> (-gt) Greater than
< (-lt) Less than
> = (-ge) Greater than or equal
<= (-le) Less than or equal
== (-eq) Equal to (comparison)
!= (-ne) Not equal to
&& (-a) And
|| (-o) Or
Conditional Statement: if-then-else
fi else
commands
fi
Case Statement
case variable/expression/value in
value1) command1
command2
;;
value2) command3
;;
*) command4
esac
Loops
• Loop statements
• Involve repeating portion of the program
while loop
Executes a list of statements repeatedly
while a certain condition holds true.
Syntax:
while condition
do
command(s)
done
For loop
for loop
Executes a list of statements a fixed number of
times.
Syntax
for variable in v1 v2 v3 v4
do
Will work for list of values mentioned here
command(s)
done
Variable declaration not required
Until loop
until loop
Executes a list of statements repeatedly till
condition remains false
Syntax
until condition
do
command(s)
done
Adv Shell Scripting
String Operations
String Description
Operation
Variable Description
# check file
test -f $num3
echo $?
Command substitution
Syntax
`command`
Example
Echo “Today is `date` “
Array
•Shell supports a different type of variable called an array
variable that can hold multiple values at the same time.
Arrays provide a method of grouping a set of variables.
${array_name[*]}
${array_name[@]}
Functions
Example
#!/bin/sh
# Define your function here
Hello()
{
echo "Hello!!!!"
}
# Invoke your function
Hello
Pass Parameters to a Function