0% found this document useful (0 votes)
36 views14 pages

Introduction to Linux-Shell Programming: Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 1

This document provides an overview of a lab introduction to Linux shell programming. It outlines the learning outcomes, preparation required, facilities available, and duration of the lab. It then details over 30 common Linux commands that will be covered, including commands for date/time, calendar, echoing text, banners, users, directories, files, sorting/filtering, pipes, and communication. The commands are explained with their syntax and usage to display system information, navigate and manipulate files and directories, and communicate between users.
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)
36 views14 pages

Introduction to Linux-Shell Programming: Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 1

This document provides an overview of a lab introduction to Linux shell programming. It outlines the learning outcomes, preparation required, facilities available, and duration of the lab. It then details over 30 common Linux commands that will be covered, including commands for date/time, calendar, echoing text, banners, users, directories, files, sorting/filtering, pipes, and communication. The commands are explained with their syntax and usage to display system information, navigate and manipulate files and directories, and communicate between users.
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/ 14

Lab-1: Introduction to Linux-Shell Programming

1. Outcomes: After this lab, learner able to:


1.1. Use some common linux commands
1.2. Shell programming and run shell cripts
2. Prepare:
2.1. Install Virtual computer and Ubuntu operating system
2.2. Read most common commands linux
3. Facilities
3.1. Computer with Ubuntu operating system
4. Duration: 4 hours
5. Sequences
5.1. COMMAND
5.1.1. Date Command :This command is used to display the current data and time.
Syntax :
$date
$date +%ch
Options : -
a = Abbrevated weekday.
A = Full weekday.
b = Abbrevated month.
B = Full month.
c = Current day and time.
C = Display the century as a decimal number.
d = Day of the month.
D = Day in „mm/dd/yy‟ format
h = Abbrevated month day.
H = Display the hour.
L = Day of the year.
m = Month of the year.
M = Minute.
P = Display AM or PM
S = Seconds
T = HH:MM:SS format
u = Week of the year.
y = Display the year in 2 digit.
Y = Display the full year.
Z = Time zone .
To change the format :
Syntax :
$date „+%H-%M-%S‟
5.1.2. Calender Command :This command is used to display the calendar of the year
or the particular month of calendar year.
Syntax :
a.$cal <year>
b.$cal <month> <year>

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 1


Here the first syntax gives the entire calendar for given year & the second Syntax
gives the calendar of reserved month of that year
5.1.3. Echo Command : This command is used to print the arguments on the screen .
Syntax : $echo <text>
Multi line echo command : To have the output in the same line , the following
commands can be used
Syntax : $echo <text\>text
To have the output in different line, the following command can be used.
Syntax :
$echo “text
>line2
>line3”
5.1.4. Banner Command : It is used to display the arguments in „#‟ symbol
Syntax : $banner <arguments>
5.1.5. ’who’ Command : It is used to display who are the users connected to our
computer currently
Syntax : $who – option‟s
Options : - H–Display the output with headers.
b–Display the last booting date or time or when the system was lastely rebooted
5.1.6. ’who am i’ Command : Display the details of the current working directory
Syntax : $who am i
5.1.7. ’tty’ Command : It will display the terminal name
Syntax : $tty
5.1.8. ’Binary’ Calculator Command : It will change the „$‟ mode and in the new
mode, arithematic operations such as +,-,*,/,%,n,sqrt(),length(),=, etc can be
performed . This command is used to go to the binary calculus mode.
Syntax : $bc operations
^d
$
1 base –inputbase
0 base – outputbase are used for base conversions.
Base : decimal =1 Binary = 2 Hexa = 16
5.1.9. ’CLEAR’ Command: It is used to clear the screen
Syntax : $clear
5.1.10.’MAN’ Command: It help us to know about the particular command and its
options & working. It is like „help‟ command in window
Syntax : $man <command name>
5.1.11.MANIPULATION Command: It is used to manipulate the screen.
Syntax : $tput <argument>
Arguments :

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 2


1.Clear – to clear the screen.
2.Longname – Display the complete name of the terminal.
3.SMSO – background become white and foreground become black color.
4.rmso – background become black and foreground becomes white color.
5.Cop R C – Move to the cursor position to the specified location.
6.Cols – Display the number of columns in our terminals
5.1.12.LIST Command: It is used to list all the contents in the current working
directory
Syntax: $ ls – options <arguments>
If the command does not contain any argument means it is working in the Current
directory.
Options :
a– used to list all the files including the hidden files.
c– list all the files columnwise.
d- list all the directories.
m- list the files separated by commas.
p- list files include „/‟ to all the directories.
r- list the files in reverse alphabetical order.
f- list the files based on the list modification date.
x-list in column wise sorted order.
5.1.13.Present Working Directory Command : To print the complete path of the
current working directory
Syntax: $pwd
5.1.14.MKDIR Command: To create or make a new directory in a current directory
Syntax: $mkdir <directory name>
5.1.15.CD Command: To change or move the directory to the mentioned directory
Syntax: $cd <directory name
5.1.16.RMDIR Command: To remove a directory in the current directory & not the
current directory itself
Syntax: $rmdir <directory name>
5.1.17.CREATE A FILE: To create a new file in the current directory we use CAT
command
Syntax : $cat > <filename
The > symbol is redirectory we use cat command
5.1.18.DISPLAY A FILE: To display the content of file mentioned we use CAT
command without „>‟ operator
Syntax: $cat <filename
Options –s = to neglect the warning /error message
5.1.19.COPYING CONTENTS: To copy the content of one file with another. If file
does not exist, a new file is created and if the file exists with some data then it is
overwritten.
Syntax: $ cat <filename source> >> <destination filename>
$ cat <source filename> >> <destination filename> it is avoid
overwriting.
Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 3
Options : - -n content of file with numbers included with blank lines.
Syntax: $cat –n <filename>
5.1.20.SORTING A FILE: To sort the contents in alphabetical order in reverse order
Syntax: $sort <filename >
Option : $ sort –r <filename>
5.1.21.COPYING CONTENTS FROM ONE FILE TO ANOTHER: To copy the
contents from source to destination file . so that both contents are same.
Syntax: $cp <source filename> <destination filename>
$cp <source filename path > <destination filename path>
5.1.22.MOVE Command: To completely move the contents from source file to
destination file and to remove the source file
Syntax: $ mv <source filename> <destination filename>
5.1.23.REMOVE Command: To permanently remove the file we use this command
Syntax : $rm <filename>
5.1.24.WORD Command: To list the content count of no of lines , words, characters
Syntax: $wc<filename>
Options : -c – to display no of characters.
-l – to display only the lines.
-w – to display the no of words
5.1.25.LINE PRINTER: To print the line through the printer, we use lp command
Syntax: $lp <filename>
5.1.26.PAGE Command: This command is used to display the contents of the file
page wise & next page can be viewed by pressing the enter key
Syntax: $pg <filename>
FILTERS AND PIPES
5.1.27.HEAD : It is used to display the top ten lines of file
Syntax: $head<filename>
5.1.28.TAIL : This command is used to display the last ten lines of file
Syntax: $tail<filename>
5.1.29.PAGE : This command shows the page by page a screen full of information is
displayed after which the page command displays a prompt and passes for the
user to strike the enter key to continue scrolling
Syntax: $ls –a\p
5.1.30.MORE : It also displays the file page by page .To continue scrolling with more
command, press the space bar key
Syntax: $more<filename>
5.1.31.GREP :This command is used to search and print the specified patterns from
the file
Syntax: $grep [option] pattern <filename>
5.1.32.SORT : This command is used to sort the data in some order
Syntax: $sort<filename>

5.1.33.PIPE: It is a mechanism by which the output of one command can be


channeled into the input
of another command.

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 4


Syntax: $who | wc-l
5.1.34.TR :The tr filter is used to translate one set of characters from the standard
inputs to another.
Syntax: $tr “[a-z]” “[A-Z]”
COMMUNICATION THROUGH UNIX COMMANDS
5.1.35.MESG: Description: The message command is used to give permission to
other users to send message to your terminal
Syntax: $mesg y
5.1.36.Command: WRITE: Description: This command is used to communicate with
other users, who are logged in at the same time
Syntax: $write <user name>
5.1.37.Command: WALL: Description: This command sends message to all users
those who are logged in using the unix server
Syntax: $wall <message>
5.1.38.Command: MAIL: Description: It refers to textual information, that can be
transferred from one user to another
Syntax: $mail <user name>
5.1.39.Command: REPLY: Description: It is used to send reply to specified user.
Syntax: $reply<user name>
5.1.40.
5.2. UNIX SHELL PROGRAMMING COMMAND
5.2.1. INTRODUCTION
Shell programming is a group of commands grouped together under single filename.
After logging onto the system a prompt for input appears which is generated by a
Command String Interpreter program called the shell. The shell interprets the input, takes
appropriate action, and finally prompts for more input. The shell can be used either
interactively - enter commands at the command prompt, or as an interpreter to execute a
shell script. Shell scripts are dynamically interpreted, NOT compiled.
5.2.2. Common Shells.
 C-Shell - csh : The default on teaching systems Good for interactive systems
Inferior programmable features
 Bourne Shell - bsh or sh - also restricted shell - bsh : Sophisticated pattern
matching and file name substitution
 Korn Shell : Backwards compatible with Bourne Shell Regular expression
substitution emacs editing mode
 Thomas C-Shell - tcsh : Based on C-Shell Additional ability to use emacs to edit
the command line Word completion & spelling correction Identifying your shell.
5.2.3. Shell keywords
echo, read, if fi, else, case, esac, for , while , do , done, until , set, unset, readonly,
shift, export, break, continue, exit, return, trap , wait, eval ,exec, ulimit , umask.
5.2.4. General things SHELL
The shbang line: The "shbang" line is the very first line of the script and lets the
kernel know what shell will be interpreting the lines in the script. The shbang line consists of
a #! followed by the full pathname to the shell, and can be followed by options to control the
behavior of the shell
EXAMPLE: #!/bin/sh

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 5


Comments: Comments are descriptive material preceded by a # sign. They are in
effect until the end of a line and can be started anywhere on the line
EXAMPLE: # this text is not
# interpreted by the shell
Wildcards: There are some characters that are evaluated by the shell in a special way.
They are called shell metacharacters or "wildcards." These characters are neither
numbers nor letters. For example, the *, ?, and [ ] are used for filename expansion. The
<, >, 2>, >>, and | symbols are used for standard I/O redirection and pipes. To prevent
these characters from being interpreted by the shell they must be quoted.
EXAMPLE: Filename expansion: rm *; ls ??; cat file[1-3];
Quotes protect meta character: echo "How are you?"
5.2.5. SHELL VARIABLES :
Shell variables change during the execution of the program .The C Shell offers a
command "Set" to assign a value to a variable.
For example:
% set myname= Fred
% set myname = "Fred Bloggs"
% set age=20
A $ sign operator is used to recall the variable values.
For example:
% echo $myname will display Fred Bloggs on the screen
A @ sign can be used to assign the integer constant values.
For example:
%@myage=20
%@age1=10
%@age2=20
%@age=$age1+$age2
%echo $age
List variables
% set programming_languages= (C LISP)
% echo $programming _languages
C LISP
% set files=*.*
% set colors=(red blue green)
% echo $colors[2]
blue
% set colors=($colors yellow)/add to list
Local variables: Local variables are in scope for the current shell. When a script ends,
they are no longer available; i.e., they go out of scope. Local variables are set and assigned
values.
EXAMPLE
variable_name=value
name="John Doe"
x=5
Global variables: Global variables are called environment variables. They are set for
the currently running shell and any process spawned from that shell. They go out of scope
when the script ends

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 6


EXAMPLE
VARIABLE_NAME=value
export VARIABLE_NAME
PATH=/bin:/usr/bin:.
export PATH
Extracting values from variables: To extract the value from variables, a dollar sign is
used.
EXAMPLE
echo $variable_name
echo $name
echo $PATH
Rules : -
1.A variable name is any combination of alphabets, digits and an underscore („-„);
2.No commas or blanks are allowed within a variable name.
3.The first character of a variable name must either be an alphabet or an underscore.
4.Variables names should be of any reasonable length.
5.Variables name are case sensitive .That is, Name, NAME, name, NAme, are all
different variables
5.2.6. EXPRESSION Command
To perform all arithematic operations.
Syntax: Var = „expr$value1‟ + $ value2‟
Arithmetic: The Bourne shell does not support arithmetic. UNIX/Linux commands
must be used to perform calculations
EXAMPLE: n=`expr 5 + 5`
echo $n
Operators: The Bourne shell uses the built-in test command operators to test numbers
and strings
EXAMPLE:
Equality:
= string
!= string
-eq number
-ne number
Logical:
-a and
-o or
! not
Logical:
AND &&
OR ||
Relational:
-gt greater than
-ge greater than, equal to
-lt less than
-le less than, equal to
Arithmetic:

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 7


+, - , * , / , %
Arguments (positional parameters) Arguments can be passed to a script from the
command line. Positional parameters are used to receive their values from within the script
EXAMPLE
At the command line:
$ scriptname arg1 arg2 arg3 ...
In a script:
Echo $1 $2 $3 position parameters
Echo $* all the positional parameters
Echo $# the number of positional parameters
5.2.7. READ Statement: To get the input from the user
Syntax: read x y (no need of commas between variables)
5.2.8. ECHO Statement: Similar to the output statement. To print output to the
screen, the echo command is used. Wildcards must be escaped with either a
backslash or matching quotes.
Syntax: Echo “String” (or) echo $ b(for variable)
EXAMPLE: echo "What is your name?"
Reading user input: The read command takes a line of input from the user and
assigns it to a variable(s) on the right-hand side. The read command can accept muliple
variable names. Each variable will be assigned a word.
EXAMPLE: echo "What is your name?"
read name
read name1 name2 ...
5.2.9. CONDITIONAL STATEMENTS
The if construct is followed by a command. If an expression is to be tested, it is
enclosed in square brackets. The then keyword is placed after the closing parenthesis. An
if must end with a fi.
Syntax :
1.if : This is used to check a condition and if it satisfies the condition if then does the
next action , if not it goes to the else part
2.if…else
If cp $ source $ target
Then
Echo File copied successfully
Else
Echo Failed to copy the file.
3.nested if: here sequence of condition are checked and the corresponding performed
accordingly
if condition
then
command
if condition
then
command
else
command

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 8


fi
fi
4.case ….. esac: This construct helps in execution of the shell script based on Choice.
EXAMPLE

The if construct is:


if command
then The case command construct is:
block of statements case variable_name in
fi pattern1)
-------------------------------------- statements
if [ expression ] ;;
then pattern2)
block of statements statements
fi ;;
-------------------------------------- pattern3)
The if/else/else if construct is: ;;
if command *) default value
then ;;
block of statements esac
elif command case "$color" in
then blue)
block of statements echo $color is blue
elif command ;;
then green)
block of statements echo $color is green
else ;;
block of statements red|orange)
fi echo $color is red or orange
------------------------------ ;;
if [ expression ] *) echo "Not a color" # default
then esac
block of statements The if/else construct is:
elif [ expression ] if [ expression ]
then then
block of statements block of statements
elif [ expression ] else
then block of statements
block of statements fi
else --------------------------------------
block of statements
fi

5.2.10.LOOPS
There are three types of loops: while, until and for. The while loop is followed by a
command or an expression enclosed in square brackets, a do keyword, a block of
Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 9
statements, and terminated with the done keyword. As long as the expression is true, the
body of statements between do and done will be executed.
The until loop is just like the while loop, except the body of the loop will be executed as
long as the expression is false.
The for loop used to iterate through a list of words, processing a word and then shifting it
off, to process the next word. When all words have been shifted from the list, it ends. The
for loop is followed by a variable name, the in keyword, and a list of words then a block of
statements, and terminates with the done keyword. The loop control commands are break
and continue.
EXAMPLE:
while command
do
block of statements
done
------------
while [ expression ]
do
block of statements
done

5.2.11.Break Statement
This command is used to jump out of the loop instantly, without waiting to get the control
command
5.2.12.ARRAYS
(positional parameters) The Bourne shell does support an array, but a word list can be
created by using positional parameters. A list of words follows the built-in set command,
and the words are accessed by position. Up to nine positions are allowed.The built-in shift
command shifts off the first word on the left-hand side of the list. The individual words
are accessed by position values starting at 1.
EXAMPLE
set word1 word2 word3
echo $1 $2 $3
Displays word1, word2, and word3
set apples peaches plums
Shifts off apples
shift
Displays first element of the list
echo $1
Displays second element of the list
echo $2
Displays all elements of the list
echo $*
5.2.13.Command substitution: To assign the output of a UNIX/Linux command to a
variable, or use the output of a command in a string, back quotes are used.
EXAMPLE: variable_name=`command`
echo $variable_name
now=`date`
echo $now
echo "Today is `date`"
5.2.14.FILE TESTING: The Bourne shell uses the test command to evaluate
conditional expressions and has a built-in set of options for testing attributes of

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 10


files, such as whether it is a directory, a plain file (not a directory), a readable file,
and so forth.
EXAMPLE:
-d File is a directory
-f File exists and is not a directory
–r Current user can read the file
–s File is of nonzero size
–w Current user can write to the file
–x Current user can execute the file
#!/bin/sh
1 if [ –f file ]
then
echo file exists
fi
2 if [ –d file ]
then
echo file is a directory
fi
3 if [ -s file ]
then
echo file is not of zero length
fi
4 if [ -r file -a -w file ]
then
echo file is readable and writable
fi
5.2.15.EXECUTION OF SHELL SCRIPT
1.By using change mode command
2.$ chmod u + x sum.sh
3.$ sum.sh
or
$ sh sum.sh
5.2.16.
5.3. SHELL PROGRAMMING
5.3.1. To write a shell program to concatenate two strings
 Algorithm
o Step1: Enter into the vi editor and go to the insert mode for entering the
code
o Step2: Read the first string.
o Step3: Read the second string
o Step4: Concatenate the two strings
o Step5: Enter into the escape mode for the execution of the result and
verify the output
 Program:
echo “enter the first string”
read str1

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 11


echo “enter the second string”
read str2
echo “the concatenated string is” $str1$str2
 Sample Input
Enter first string: Hello
Enter first string: World
 Sample Output
The concatenated string is HelloWorld

5.3.2. COMPARISON OF TWO STRINGS
 Aim: To write a shell program to compare the two strings
 Algorithm:
o Step1: Enter into the vi editor and go to the insert mode for entering the
code
o Step2: Read the first string.
o Step3: Read the second string
o Step4: Compare the two strings using the if loop
o Step5: If the condition satisfies then print that two strings are equal else
print two
strings are not equal.
o Step6: Enter into the escape mode for the execution of the result and
verify the output
 Program:
echo “enter the first string”
read str1
echo “enter the second string”
read str2
if [ $str1 = $str2 ]
then
echo “strings are equal”
else
echo “strings are unequal”
fi
 Sample input:
Enter first string: hai
Enter second string: hai
 Sample output:
The two strings are equal
 Sample input 2:
Enter first string: hai
Enter second string: cse
 Sample output 2:
The two strings are not equal

5.3.3. MAXIMUM OF THREE NUMBERS
 Aim: To write a shell program to find greatest of three numbers

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 12


 Algorithm:
o Step1: Declare the three variables.
o Step2: Check if A is greater than B and C.
o Step3: If so print A is greater.
o Step4: Else check if B is greater than C.
o Step5: If so print B is greater.
o Step6: Else print C is greater.
 Program:
echo "enter A"
read a
echo "enter B"
read b
echo "enter C"
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "A is greater"
elif [ $b -gt $a -a $b -gt $c ]
then
echo "B is greater"
else
echo "C is greater"
fi
 Sample Input
Enter A:23
Enter B:45
Enter C:67
 Sample output
C is greater
5.3.4. ARITHMETIC OPERATIONS USING CASE
 Aim: To write a shell program to perform the arithmetic operations using case
 Algorithm:
o Step 1: Read the input variables and assign the value
o Step 2: Print the various arithmetic operations which we are going to
perform
o Step 3: Using the case operator assign the various functions for the
arithmetic operators.
o Step 4: Check the values for all the corresponding operations.
o Step 5: Print the result and stop the execution.
o
 Program :
echo 1.Addition
echo 2.Subraction
echo 3.Multiplication
echo 4.Division
echo enter your choice

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 13


read a
echo enter the value of b
read b
echo enter the value of c
read c
echo b is $b c is $c
case $a in
1)d=`expr $b + $c`
echo the sum is $d
;;
2)d=`expr $b - $c`
echo the difference is $d
;;
3)d=`expr $b \* $c`
echo the product is $d
;;
4)d=`expr $b / $c`
echo the quotient is $d
;;
esac
 Sample Input:
1.Addition
2.Subraction
3.Multiplication
Division
Enter your choice:1
Enter the value of b:3
Enter the value of c:4
b is 3 c is 4
the sum is 7
 Sample ouput
b is 3 c is 4
the sum is 7

5.3.5.

Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 14

You might also like