Operating System Lab 03 Shell Script I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Sumanta Das

Dept. of CSE, NSEC [email protected]

Linux Operating System


Shell Scripts (Lab III)
Part I

What is shell script?


A shell script is just a text file, which contains commands.

Scripting lets you automate complex, repetitive or tedious procedures. It also


encapsulates knowledge about how things are done – once you've written a script other
users can take advantage of it. It eliminates errors due to typographical errors or
misremembering. Scripting makes UNIX/Linux systems much easier to administer.

Example 1:
Create a file called test.sh containing the following lines (use any editor like vi):
clear
cd /root
cal
To execute a shell script:
sh your-script-name (e.g.: sh test.sh)

After writing shell script, we may set execute permission for the script as follows using
chmod command:
$ chmod +x your-script-name
$ chmod 755 your-script-name

Note: This will set read write execute (7) permission for owner, for group and
other permission is read and execute only (5).

Now we may execute our script as


./your-script-name (e.g.: $ ./test.sh)

NOTE: In the last syntax ./ means current directory, But only . (dot) means
execute given command file in current shell without starting the new copy of
shell, The syntax for . (dot) command is: .command-name

Example 2: Write a shell script that will print "Knowledge is Power" on screen.
#
# My first shell script
#
clear
echo "Knowledge is Power"
#End script

Page 1 of 5
Sumanta Das
Dept. of CSE, NSEC [email protected]
Using comment-text
Any text followed by # is considered as comment. Comment gives more information
about script, logical explanation about shell script but not executed.

To print message or value of variables on screen


We may use echo command for this. General form of echo command is: echo "Message"

Note: For shell script file the extension (.sh) should be used to easily identify the
shell script files. The extension is not mandatory.

Example 3:
Script to print user information who currently login, current date & time
Ans:
#
# Script to print user information who currently login , current date & time
#
clear
echo "Hello $USER"
echo "Today is \c ";date
echo "Number of user login : \c" ; who | wc -l
echo "Calendar"
cal
exit 0
#End script

At the end of the script, the statement exit 0 is used to sop the script with exit status.

NOTE: By default in Linux if particular command/shell script is executed, it


return two type of values which is used to see whether command or shell script
executed is successful or not. This value is known as Exit Status. The value may
be:
(1) zero (0), command is successful.
(2) nonzero, command is not successful or some sort of error has occurred.
To find out exit status of command or shell script use: $? (special variable of
shell).
e.g.: $ echo $?

Shell Variables

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.

Page 2 of 5
Sumanta Das
Dept. of CSE, NSEC [email protected]

Some System variables are:


HOME (Our home directory), LINES (No. of columns for our screen, Default=25),
COLUMNS (No. of columns for our screen, Default =80), PATH(Our path settings), etc.

Example: To print your home directory location: echo $HOME

Using User defined variables (UDV)


To print or access UDV use $.

Define variable var1 and n as follows:


$ var1=Bus
$ n=10

To print contains of variable 'var1' type


$ echo $ var1 (It will print 'Bus')
$ echo $n (prints containt of variable 'n' )

Use echo Command for formatted output


The echo command is to display text or value of variable.
Syntax: echo [options] [string, variables...]
Options
-n Do not output the trailing new line.
-e Enable interpretation of the following backslash escaped characters in the strings:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash

e.g. $ echo -e "An apple a day keeps away \a\t\tdoctor\n"

Arithmetic Operations
Use to perform arithmetic operations use expr command.
Examples:
$ expr 1 + 3
$ expr 20 % 3
$ expr 10 \* 3
$ echo `expr 6 + 3`
expr 20 %3 # Remainder division. Read as 20 mod 3 and remainder is 2.
expr 10 \* 3 # Multiplication operation. Use \* and not * since it is a wild card.

Page 3 of 5
Sumanta Das
Dept. of CSE, NSEC [email protected]
Note: the expr command uses ` (back quote) sign not the (single quote i.e. ') sign. Back
quote is generally found on the key under tilde (~) on PC keyboard. There are three types
of quotes
" (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

Example:
$ echo "Today is date" # Can't print message with today's date.
$ echo "Today is `date`". # It will print: today's date as, Today is Tue Jan...

The read Statement


Used to get input (data from user) from keyboard and store (data) to variable.

Example 4:
#
#Script to read your name from key-board
#
echo "Your first name please:"
read fname
echo "Hello $fname, Lets be friend!"

Redirection of Standard output/input i.e. Input - Output redirection


Mostly all command gives output on screen or take input from keyboard, but in Linux it's
possible to send output to file or to read input from file. There are three main redirection
symbols >,>>,<.

To output Linux-commands result (output of command or shell script) to file. Note that if
file already exist, it will be overwritten without any warning else new file is created.
e.g. ls > myfiles
Now if 'myfiles' file exist in your current directory it will be overwritten without any type
of warning.

>> Redirector Symbol


To output Linux-commands result to END of file. Note that if file exist, it will be opened
and new information/data will be written to END of file, without losing previous
information/data, And if file is not exist, then new file is created.
e.g. date >> myfiles

< Redirector Symbol


To take input to Linux-command from file instead of key-board.
e.g. cat < myfiles # To take input for cat command

We can also use above redirectors simultaneously as follows


Create text file sname as follows

Page 4 of 5
Sumanta Das
Dept. of CSE, NSEC [email protected]

$cat > sname


vivek
ashish
zebra
babu
Press CTRL + D to save.

Now issue following command.


$ sort < sname > sorted_names
$ cat sorted_names
ashish
babu
vivek
zebra

In above example sort ($ sort < sname > sorted_names) command takes input from
sname file and output of sort command (i.e. sorted names) is redirected to sorted_names
file.

Wild cards (Filename Shorthand or meta Characters)

Wild card
Meaning Examples
/Shorthand
$ ls * will show all files
will show all files whose first name
$ ls a*
Matches any string is starting with letter 'a'
* or group of will show all files having extension
characters. $ ls *.c
.c
will show all files having extension
$ ls ut*.c
.c but file name must begin with 'ut'.
will show all files whose names are
$ ls ?
1 character long
Matches any single
? will show all files whose names are
character.
$ ls fo? 3 character long and file name begin
with fo
Matches any one of
will show all files beginning with
[...] the enclosed $ ls [abc]*
letters a,b,c
characters
A pair of characters
Will show all files name beginning
[..-..] separated by a minus $ ls /bin/[a-c]*
with letter a,b or c like
sign denotes a range.

------o------

Page 5 of 5

You might also like