Shell Scripting-8

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Shell Scripting

1) Write a shell script to print files of a directory,show logged in user,and your current working
directory?
Shell
2) Interactive Shell script- A worthwhile program needs to talk to the user,so two very basic words
in the shell vocabulary are read (to accept input ) and echo (to display output).
#This is interactive shell script
echo What is your name ?
read name
echo Hello My name is $name ,Happy Programming

Shell Variables
They are an integral part of Shell Programming.They provide the ability to store and manipulate
information within a shell program.You can create and destroy any no of variables as needed to solve
the problem at hand.

Rules for builing shell variables-

 The name of a variable can contain only letters (a to z or A to Z),


 numbers ( 0 to 9) or the underscore character ( _).
 There is no limit on the length of variable name.
 By convention, Unix shell variables will have their names in UPPERCASE.
Eg- si_int,m_hra,pop_e_89

Shell Keywords(Reserved Words)


Keywords are the words whose meaning has already been explained to the shell.These keywords cannot
be used as variable name.

 echo
 read
 set
 unset
 readonly
 shift
 export
 if
 fi
 else
 while
 do
 done
 for
 until
 case
 esac
 break
 continue
 exit
 return
 trap
 wait
 eval
 exec
 ulimit
 umask

Another way of assigning values to variable


We can assign values by simple assignment operator.For eg.

name=mandar

age =20

dirname=/usr/aa5

(There should be no spaces on either side of =).If the variable already exist,it will store the new value
replacing the old value which the variable contains.)

There are 2 types of variables in unix-

1)Unix Defined Variables

2)User Defined Variables


Unix Defined Variables

The list of all system variables and their values can be displayed by saying at the $prompt.

Set command

User Defined Variables


Defined by user.

Tips and Tricks


 All Shell Variables are string variables .If a=20,a is treated not as a number but a string of
character 2 and 0.Hence to carry out arithmetic operations we need to use expr command.
 A=”Two words” ;echo $a(When 2 words enclose in double quotes)
 name=john age=10
echo $name $age
We can assign more than one assignment in a line .
 All Variables defined in a shell script die the moment ,shell script execution is over.
 Null Variable-A variable which is defined but is not given any value.
$d=””
$d=’’
$d=
When we echo a null variable only blank line appears on the screen.
Unchanging variables
When we want to have a constant of fixed value.

So, $a=20

$readonly a

When the variables are made readonly ,the shell does not allow us to change their values.All such
variables can be listed by entering readonly at the dollar prompt.

Positional Paramters
When we need to convey information to a program that can be done by specifying arguments at the
command line.

There are some variables defined by the shell.They are nine in number named $1 to $9.

Eg- set Hello I am Rajiv Gupta

Echo $1 $2 $3 $4 $5

Q1- Write a shell script to accept two filenames from the command line ,copies the first file to second
one and then display it.

./ss3.sh <source> <target>

cp $1 $2

cat $2

Q2-set `cat lucky`

Echo $1 $2 $3 $4 $5

Q3- Write a shell script that reads a filename from the command line and changes the name to
filename.aa1 where aa1 is the logname of the user.

Ans- Usage : $SS5 <filename>

name=$1

set `who am i`

mv $name $name.$1
Displaying date in desired Format
Set `date`

Echo $1 $2 $3 $4

Echo $2 $4 $6

# To count how many positional parametres were set we use- echo $#

#to see all the parametres – echo $* or echo $@

Using Shift on positional parametres


Shift is a builtin command in bash which after getting executed, shifts/move the command line
arguments to one position left. The first argument is lost after using shift command. This command takes
only one integer as an argument.

This command is useful when you want to get rid of the command line arguments which are not needed
after parsing them.

Here is the shell script to solve the problem-

!/bin/bash

# total number of command-line arguments

echo "Total arguments passed are: $#"

# $* is used to show the command line arguments

echo "The arguments are: $*"

echo "The First Argument is: $1"

shift 2

echo "The First Argument After Shift 2 is: $1"

shift

echo "The First Argument After Shift is: $1"

Note- echo $* is used to show the total no of command line arguments passed.
Calculations in Script
#here is an example of floating point arithmetic operations

a=10.5

b=3.5

c=`echo $a+$b|bc`

d=`echo $a-$b|bc`

e=`echo $a\*$b|bc`

f=`echo $a/$b|bc`

echo $c $d $e $f

Read and echo Revisited


If we want the output of single echo statement to be split across lines we can use newline escape
sequence.

Practice this- echo “I like work ……\n I can sit and watch it for hours”

Positioning the Cursor


If we want the cursor to wait and the end of the echoed line,say while asking the users choice from the
presented menu..The trick is—

$echo “Enter Your choice…….\c”

Here the cursor waits as the line ends and not on the second line.

 Escape Sequence for the bell- $echo “\07”


 Escape sequence for the bold- $echo “\033[1m This is bold”

Escaping newline in echo


By default, echo appends a newline to the end of its output text. When using escape sequences, use
echo as echo -e "string containing escape sequences".

Consider the following example:

echo -e "1\t2\t3"(t stands for tab space)

Output- 1 2 3
Predefined Variables and Access
All programming languages use variables to retain data for later use or modification. Unlike compiled
languages, most scripting languages do not require a type declaration before a variable is created. The
type is determined by usage. The value of a variable is accessed by preceding the variable name with a
dollar sign. The shell defines several variables it uses for configuration and information like available
printers, search paths, and so on. These are called environment variables.

 All environment variable are in Upper case letter.


 Command used- env
 We can define the env variables if we wanna set through export Command
Syntax- export VAR_1=30
 If we want to add a new path in $PATH variable then
Syntax- PATH=$PATH:/home/usr/bin”
export PATH
echo $PATH
Usually $PATH is defined in .bashrc /etc/profile and /etc/environment

Accessing Value from the variable


var=”Hello World”

echo $var or echo ${var}

Finding the length of a string


a=323243483858; echo ${#c}

Identifying the current Shell


echo $SHELL or echo $0

Let command
Simple Script:-

1. a=5
2. b=10
3. let result=a+b
4. echo $result
For increment- let result++ ,let no+=6

For decrement- let result—,let no-=6

Three Commands for performing mathematical operations-


 bc
 expr
 let

Tee command
Tee command reads the standard input and writes it to both the std output and one or more files.

 ls |tee logfile |sort


 ls |tee logfile newlogfile|sort
 ls|tee file1 file2 /dev/tty|sort > file3
 Cat file1 file2|tee –a file3|more

Alias Command
Alias are like custom shortcuts used to represent a command (or set of commands) executed with or
without custom options.It is like a shortcut command which will have same functionality as if we
are writing the whole command.

Eg- alias l='ls -l|sort'


 Alias –p displays all the aliases .
Setting an alias in this way only works for the life of a shell session.

You might also like