Sunteți pe pagina 1din 23

Linux Shell Scripting

Before You Start Scripting


– You have Basic Linux knowledge as like commands, vi editor...etc.
– Aim of this note is only basic knowledge for Shell scripting.

Chapter 1: Quick Introduction Of Shell Scripting

What is Shell Script ?


--Shell Script is series of command written in plain text file.
--It is a command language interpreter that executes commands read from the
standard input device such as keyboard or from a file.

How to write shell script ?


-Following steps are required to write shell script:
1) Use any editor like vi or mcedit to write shell script.
2) After writing shell script set execute permission for your script as
follows.
syntax:
chmod permission your-script-name
Examples:
$ chmod +x your-script-name
$ chmod 755 your-script-name
3) Execute your script as
syntax:
bash your-script-name
sh your-script-name
./your-script-name
Examples:
$ bash bar
$ sh bar
$ ./bar
Shebang- The #! syntax used in scripts to indicate an interpreter for execution
under UNIX / Linux operating systems. Most
Linux shell and perl / python script starts with the following line:
#!/bin/bash

Now we write our first script that will print "Welcome in Vyomlabs" on
screen.

$ vi first.sh
#
# My first shell script
#
clear
echo "Welcome in Vyomlabs"

After saving the above script, you can run the script as follows:
$ chmod 755 first
$ ./first.sh

Shell Types

Several shells are available for Linux including:


• BASH ( Bourne-Again SHell ) - Most common shell in Linux. It's Open
Source.

• CSH (C SHell) - The C shell's syntax and usage are very similar to the
C programming language.

• KSH (Korn SHell) - Created by David Korn at AT & T Bell Labs. The
Korn Shell also was the base for the POSIX Shell standard
specifications.
• TCSH - It is an enhanced but completely compatible version of the
Berkeley UNIX C shell (CSH).

Variables in Shell
-In Linux (Shell), there are two types of variable:
(1) System variables - Created and maintained by Linux itself. This type of variable
defined in
CAPITAL LETTERS.
(2) User defined variables (UDV) - Created and maintained by user. This type of
variable defined in
lower letters.

System Variable
You can see system variables by giving command like $ set

$ set

BASH=/bin/bash
BASH_VERSION=1.14.7(1)
COLUMNS=80
HOME=/home/vivek
LINES=25
LOGNAME=students
OSTYPE=Linux
PATH=/usr/bin:/sbin:/bin:/usr/sbin
PS1=[\u@\h \W]\$
PWD=/home/students/Common
SHELL=/bin/bash
USERNAME=vivek
User defined variables
(UDV)

To define UDV use following syntax


Syntax:
variable name=value
'value' is assigned to given 'variable name' and Value must be on
right side = sign.
Example:
$ no=10 # this is ok
$ 10=no # Error, NOT Ok, Value must be on right side of = sign.
To define variable called 'vech' having value Bus
$ vech=Bus
To define variable called n having value 10
$ n=10
Rules for Naming variable name

(1) Variable name must begin with Alphanumeric character or


underscore character (_), followed by one
or more Alphanumeric character. For e.g. Valid shell variable are as
follows
HOME
SYSTEM_VERSION
vech
no

(2) Don't put spaces on either side of the equal sign when
assigning value to variable. For e.g. In
following variable declaration there will be no error
$ no=10
But there will be problem for any of the following variable
declaration:
$ no =10
$ no= 10
$ no = 10

(3) Variables are case-sensitive


4) You can define NULL variable as follows (NULL variable is
variable which has no value at the time
of definition) For e.g.
$ vech=
$ vech=""
Try to print it's value by issuing following command
$ echo $vech
Nothing will be shown because variable has no value i.e. NULL
variable.
(5) Do not use ?,* etc, to name your variable names.

Some important Commands


1) echo command:

Use echo command to display text or value of variable

2) Read statement

Use to get input (data from user) from keyboard and store
(data) to variable.
Syntax:
read variable1, variable2,...variableN

Let's See Example:

$ vi vyom.sh
#
#Script to read your name from key-board
#
echo "Your first name please:"
read fname
echo "Hello $fname, welcome in Vyomlabs"
Quotes in Shell Scripts
There are three types of quotes

Double Quotes = “ “

Single quotes = ' '

Back quote =` `

"Double Quotes" - Anything enclose in double quotes removed


meaning of that characters (except \ and $).

'Single quotes' - Enclosed in single quotes remains unchanged.

`Back quote` - To execute command

Wild cards in Shell Scripts


1) * Matches any strings or group of characters
For e.g
ls * - will show all files

2) ? Matches any single character.


For. e.g
ls ? - will show all files whose names are 1 character
long

3) […..] - Matches any one of the enclosed characters


For e.g
ls [ abc ]* - will show all files beginning with letters a,b,c

Chapter 2: Shell Programming


Mathematical Operators

Operator Description Example Evaluates To


+ Addition echo $(( 20 + 5 )) 25
- Subtraction echo $(( 20 - 5 )) 15
/ Division echo $(( 20 / 5 )) 4
* Multiplication echo $(( 20 * 5 )) 100
% Modulus echo $(( 20 % 3 )) 2

For e.g
Accept Two Numbers form users (keybord) and multiply them .
Vi vyom.sh
#!/bin/bash
read -p "Enter two numbers : " x y
ans=$(( x * y ))
echo "$x + $y = $ans"

Save and close the file. Run it as follows:


chmod -R 755 vyom.sh
./vyom.sh
test command or [ expr ]
test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0),
otherwise
returns nonzero for false.
Syntax:
test expression OR [ expression ]

test or [ expr ] works with


1.Integer ( Number without decimal point)
2.File types
3.Character strings
Mathematical Operator Meaining Test Statement
-eq is equal to if test 5 -eq 6
-ne is not equal to if test 5 -ne 6
-lt is less than if test 5 -lt 6

-le is less than or equal to if test 5 -le 6

-gt is greater than if test 5 -gt 6

-ge is greater than or equal to if test 5 -ge 6

string Comparisons Operators

Operator Meaning
string1 = string2 string1 is equal to string2
string1 != string2 string1 is NOT equal to string2
string1 string1 is NOT NULL or not defined
-n string1 string1 is NOT NULL and does exist
-z string1 string1 is NULL and does exist
file and directory types Operators

Test Meaning
-s file Non empty file
-f file Is File exist or normal file and not a directory
-d dir Is Directory exist and not a file
-w file Is writeable file
-r file Is read-only file
-x file Is file is executable

Logical Operators

Operator Meaning
! expression Logical NOT
expression1 -a expression2 Logical AND
expression1 -o expression2 Logical OR
Decision making in shell script

if...else...fi

If given condition is true then command1 is executed otherwise command2 is executed.


Syntax:
if condition
then
condition is zero (true - 0)
execute all commands up to else statement
else
if condition is not true then
execute all commands up to fi
fi

Let's take a example:


Write a Script to decide given number is positive or negative.
Vi demo.sh
if test $1 -gt 0
then
echo "$1 number is positive"
else
echo "$1 number is negative"
fi
Try it as follow
chmod 755 demo.sh
./demo.sh 5
In this Example we take number from commandline. So what is commandline argument let's see.

In Above example :
./demo.sh 5
demo.sh --- Shell Script name($0)
5 ---------- First commandline argument ($1)
In Shell Scripting we refer this as follow.
Demo.sh it is $0
5 it is $1
Command line Argument:
$0 is the name of the command
$1 first parameter
$2 second parameter
$ 3 third parameter etc. etc
$# total number of parameters
$@ all the parameters will be listed

Loops in Shell Scripts


"Computer can repeat particular instruction again and again, until particular condition satisfies.
A group of instruction that is executed repeatedly is called a loop."
Bash supports:
1) for loop
2 )while loop

The for loop syntax is as follows:


for var in item1 item2 ... itemN
do
command1
command2
....
...
commandN
done

The for loop three-expression syntax


( As like C language)

for (( EXP1; EXP2; EXP3 ))


do
command1
command2
command3
done
The above syntax is characterized by a three-parameter loop control expression; consisting of an
initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3).

For e.g
Vi vyom.sh
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times in vyomlabs."
done
Save and close the file. Run it as follows:
chmod -R 755 vyom.sh
./vyom.sh

The while loop syntax


The syntax is:
while [ condition ]
do
command1
command2
..
....
commandN
done

For e.g
vi while.sh
#!/bin/bash
# set n to 1
n=1
# continue until $n equals 5
while [ $n -le 5 ]
do
echo "Welcome $n times in vyomlabs."
n=$(( n+1 )) # increments $n
done

Save and close the file. Run it as follows:


chmod 755 while.sh
./while.sh
Write a shell script that, given a file name as the argument will count English language articles
such As 'A', 'An'
and 'The'
Advance Shell scripting

After learning basis of shell scripting, it's time to learn more


advance features of shell scripting.

Functions

Function is series of instruction/commands. Function performs


particular activity in shell

To define function use following syntax:

Syntax:
function-name ( )
{
command1
command2
.....
...
commandN
return
}

Where function-name is name of you function, that executes


series of commands. A return statement will
terminate the function.

Example:
Type SayHello() at $ prompt as follows

$ SayHello()
{
echo "Hello $LOGNAME, Have nice day"
return
}

To execute this SayHello() function just type it name as follows:


$ SayHello
Hello vivek, Have nice day.
Cut utility

Cut utility cuts out selected data from source file.

General Syntax of cut utility:

Syntax:
cut -f{field number} {file-name}

Use of Cut utility:


Selecting portion of a file.

For E.g
We have 2 files with following data.( using Vi editor)

[oracle@r0491 ~]$ cat sname


Sr.No Name
11 Vivek
12 Renuka
13 Prakash
14 Ashish
15 Rani

[oracle@r0491 ~]$ cat smark


Sr.No Mark
11 67
12 55
13 96
14 36
15 67
Suppose from sname file you wish to print name of student on-
screen
Excute Following Command.

[oracle@r0491 ~]$ cut -f2 sname

See the output.

Paste utility

Paste utility is useful to put textual information together located in


various files.

General Syntax of paste utility:


Syntax:
paste {file1} {file2}

Use of paste utility:


Putting lines together.

For.eg

[oracle@r0491 ~]$ paste sname smark


Join utility

General Syntax of join utility:


Syntax:
join {file1} {file2}

Use of join utility:


The join utility joins, lines from separate files.

Note- that join will only work, if there is common field in both file
and if values are identical to each other.

For .e.g
[oracle@r0491 ~]$ join sname smark
awk utility
Use of awk utility:
To manipulate data.

General Syntax of awk utility:


Syntax:
awk 'pattern action' {file-name}

Suppose we have following files:


[oracle@r0491 ~]$ cat food
egg order 4
cacke good 10
cheese okay 4
pen good 12
floppy good 5

After crating file issue command


[oracle@r0491 ~]$ awk '/good/ { print $3 }' food

Sed utility

S-ar putea să vă placă și