You are on page 1of 19

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. What is Unix
UNIX is a powerful operating system originally developed at AT&T Bell Labs. It is very
popular among the scientific, engineering, and academic communities due to its multi-
user and multi-tasking environment, flexibility and portability, electronic mail and
networking capabilities, and the numerous programming, text processing and scientific
utilities available. The UNIX system is mainly composed of three different parts: the kernel,
the file system, and the shell.
5.1. The kernel is that part of the system which manages the resources of whatever
computer system it lives on, to keep track of the disks, tapes, printers, terminals,
communication lines and any other devices.
5.2. The file system is the organising structure for data. The file system is perhaps the most
important part of the UNIX operating system. The file system goes beyond being a
simple repository for data, and provides the means of organizing the layout of the data
storage in complex ways.
5.3. The shell is the command interpreter. Although the shell is just a utility program, and
is not properly a part of the system, it is the part that the user sees. The shell listens
to your terminal and translates your requests into actions on the part of the kernel
and the many utility programs
6. More about Unix File System
A file system is a logical organization of storage space designed to contain files in
directories. The UNIX file system is quite similar to that of MS-DOS or Windows. It is
organized hierarchically (inverted tree) into directories for efficient organization.
However, in Windows, there are many logical trees represented by drive letters such as C:,
D:, H:, etc… . In Unix, all file systems (Hard Disks, CD-ROMs, Floppy Disks, ZIP drives,
network mounts, etc …) are “mounted” onto one logical tree. The top of the hierarchy is
traditionally called root which is represented by a / (slash).

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


In Unix, everything is treated as a file. A directory is a file. It is a file that contains a list of files
and information belonging to those files. This would include things like who “owns” (created)
the file, how long it is, and who can use it. Since a directory is simply a list of files, it can
contain any file in it, including other directories.
7. Sequences
7.1. COMMANDS
7.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.

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


y = Display the year in 2 digit.
Y = Display the full year.
Z = Time zone .
To change the format :
Syntax:
$date „+%H-%M-%S‟
7.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>
Here the first syntax gives the entire calendar for given year & the second Syntax
gives the calendar of reserved month of that year
7.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”
7.1.4. Banner Command: It is used to display the arguments in “#‟ symbol
Syntax: $banner <arguments>
7.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
7.1.6. ’who am i’ Command: Display the details of the current working directory
Syntax: $who am i
7.1.7. ’tty’ Command: It will display the terminal name
Syntax: $tty
7.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
$

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


1 base –inputbase
0 base – outputbase are used for base conversions.
Base : decimal =1 Binary = 2 Hexa = 16
7.1.9. ’CLEAR’ Command: It is used to clear the screen
Syntax: $clear
7.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>
Exam: $man ls
7.1.11. 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.
7.1.12. Present Working Directory Command : To print the complete path of the
current working directory
Syntax: $pwd
7.1.13. MKDIR Command: To create or make a new directory in a current directory
Syntax: $mkdir <directory name>
Example: To make a subdirectory called ics431 in your current working directory type
$ mkdir ics431
Now to see the directory you have just created, type
$ ls
7.1.14. CD Command: To change or move the directory to the mentioned directory
Syntax: $cd <directory name
Example: To change to the directory you have just made, type
$ cd ics431
Type ls to see the contents (which should be empty)
Exercises (1b):
1. Make another directory inside the ics431 directory called “LabOS” then make
“LabOS” your current working directory.
2. Now type the command:

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


$ cd ..
followed by:
$ ls
In which directory you are located now?
3. Type the following command
$ cd /etc/fs
followed by:
$ ls
In which directory you are located now?
4. Now enter the command:
$ cd
In which directory you are located now?
5. Write a single Unix command to make “LabOS” your current working directory
7.1.15. RMDIR Command: To remove a directory in the current directory & not the
current directory itself
Syntax: $rmdir <directory name>
7.1.16. CREATE A FILE: To create a new file in the current directory we use CAT
command (The command cat can be used to display the contents of a file on
the screen)
Syntax: $cat > <filename
The > symbol is redirectory we use cat command
Example: To verify your wok in previous section, you can view the content of hello.txt
by typing:
$ cat hello.txt
The cat command is useful for displaying short files of a few lines. To display longer
files use less or more commands.
7.1.17. 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
7.1.18. 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.
Options : - -n content of file with numbers included with blank lines.
Syntax: $cat –n <filename>
7.1.19. SORTING A FILE: To sort the contents in alphabetical order in reverse order

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


Syntax: $sort <filename >
Option : $ sort –r <filename>
7.1.20. 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>
Syntax 1: ( copy a file to another file)
$ cp file1 file2
where file1 is the name of an existing file and file2 is the name for the new copy of
that
file. The original file will remain unchanged and a copy will be placed in file2. If file1
and file2 are not in current directory, then you have to specify its pathname.
Syntax 2: (copy a file to another directory)
$ cp file directory
where file is the name of an existing file and directory is the name for the destination
directory. The original file will remain unchanged and a copy will be placed in that
directory
7.1.21. 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>
To move a file from one place to another, use the mv command. This has the effect of moving
rather than copying the file, so you end up with only one file rather than two.
It can also be used to rename a file, by moving the file to the same directory, but giving it a
different name.
Example: We are going to move the file “salam.bak” to your backup directory, type
$ mv salam.bak backup
Now what is the content of your current directory? What is the content of your backup
directory?
7.1.22. REMOVE Command: To permanently remove the file we use this command
Syntax : $rm <filename>
To delete (remove) a file, use the rm command. However, to delete a directory use the rmdir
command. There is one constraint to delete a directory; the directory must be empty.
Example 1: We know that your backup directory contains two files named “salam.txt” and
“salam.bak”. We are going to delete the file “salam.txt” and, as an exercise, delete the second
file.
$ rm backup/salam.txt
Example 2: If you successfully delete the two files, you can delete the backup directory. To
delete the backup directory, type:
$ rmdir backup
Exercises (1e):

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


1. Delete the file named “salam.txt” from directory “ics431”
2. create a directory named “tempdir” by using mkdir then remove it
7.1.23. 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
7.1.24. LINE PRINTER: To print the line through the printer, we use lp command
Syntax: $lp <filename>
7.1.25. HEAD : It is used to display the top ten lines of file
Syntax: $head<filename>
7.1.26. TAIL : This command is used to display the last ten lines of file
Syntax: $tail<filename>
7.1.27. MORE : It also displays the file page by page .To continue scrolling with more
command, press the space bar key
Syntax: $more<filename>
7.1.28. GREP :This command is used to search and print the specified patterns from
the file
Syntax: $grep [option] pattern <filename>
7.1.29. SORT : This command is used to sort the data in some order
Syntax: $sort<filename>
7.1.30. PIPE: It is a mechanism by which the output of one command can be
channeled into the input of another command.
Syntax: $who | wc-l
7.1.31. 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
7.1.32. MESG: Description: The message command is used to give permission to
other users to send message to your terminal
Syntax: $mesg y
7.1.33. Command WRITE: Description: This command is used to communicate with
other users, who are logged in at the same time
Syntax: $write <user name>
7.1.34. Command WALL: Description: This command sends message to all users
those who are logged in using the unix server
Syntax: $wall <message>
7.1.35. Command MAIL: Description: It refers to textual information, that can be
transferred from one user to another
Syntax: $mail <user name>
7.1.36. Command REPLY: Description: It is used to send reply to specified user.
Syntax: $reply<user name>
8. UNIX SHELL PROGRAMMING COMMAND

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


8.1.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.
8.1.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.
 The way to determinte shell: echo $SHELL
8.1.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.
8.1.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
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?"
8.1.5. SHELL VARIABLES :
Like the general variables in other programming languages, the Shell script also has
variables. Variables store data or point to the location of data. The shell allows for the
creation, execution, and deletion of the variables.
Variable Names:The variable name can have only letters (a to z or A to Z), numbers (0 to
9), or the underscore character (_). The wrong character usage in the variable name will
cause a syntax error.

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


Defining Variable:To define a variable, use the syntax below:
Syntax: variable_name=variable_value
Example: NAME="ABC"
Accessing the variables:To access the variables, use the "$" as a prefix to the variable
name.
Example: The example below shows a script that performs the following function:
Declares a variable with a value assigned to it.
Command
#!/bin/sh
NAME=" ABC "
echo $NAME
Output
The above script executes to print,
ABC
Read-Only Variables: In order to make the variables static, that is, whose value cannot be
altered, the read-only command is used in the shell scripting.
Example
The script below shows an example to change a normal variable to "read-only".
Command
#!/bin/sh
NAME="ABC"
readonly NAME
NAME="DBC"
Here, we are attempting to change the “read-only” variable value from “ABC” to “DBC”
Output
The output generated says:
/bin/sh: NAME: This variable is read only.
Unsetting Variables
Unsetting the variable makes the variable to be removed from the list of variables, by the
shell. It is almost like deleting the value of the variable, as you will no more be able to access
its value.
Unsetting cannot be performed on the "read-only" variables.
Syntax
unset variable_name
Example
The example below shows a script that unsets a variable and tries to print its value
Command
#!/bin/sh
NAME="Reva"
unset NAME
echo $NAME
Output
This gives no output.
Types of Variables
There are three types of variables on a running script. They are:
 Local variables: Local variables are present in the current instance of the shell. They
are set by the command prompt.

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


 Environment variables: These are the variables defined by the shell script. Only those
required will be defined. They are available to all the child processes of the shell.
 Shell variables: These are special variables required for the proper functioning of the
shell. They can be either local variables or environment variables.
8.1.6. Shell Comments
 Shell comments make the code more readable and user-friendly. The scripting best
practices include adding comments at short intervals, to explain the code in brisk.
 Example
#!/bin/bash
# Author: Reva
# Script follows here:
echo "Hello World"
 The code is interpreted by Shell. That is, it is not compiled. The interpreter ignores the
comments and executes the commands directly.
8.1.7. Extended Shell Scripts
 The shell is a real programming language, which has all the constructs of a normal
programming language such as the loops, iterations, control structures, etc.
 All the scripts will not be as simple as the ones shown above. Of course, the complexity
increases with the advancement and application.
 The advanced shell scripts perform some advanced and more intuitive operations, which
increase the usability of the code.
 The "read" command used below, takes the input from the keyboard and assigns it to the
variable on the go.
 Below is an example of it.
 Command
#!/bin/sh
echo "what is your name?"
read name
echo "How do you do, $name?"
read remark
echo "I am $remark too!"
8.1.8. Arithmetic Operators
There are various operators supported by each shell. We will discuss in detail about Bourne
shell (default shell) in this chapter. We will now discuss the following operators −
 Arithmetic Operators
 Relational Operators
 Boolean Operators
 String Operators
 File Test Operators
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations
but it uses external programs, either awk or expr. The following example shows how to add
two numbers −
#!/bin/sh
val=`expr 2 + 2`

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


echo "Total value : $val"
The above script will generate the following result −
Total value : 4
The following points need to be considered while adding −
 There must be spaces between operators and expressions. For example, 2+2 is not
correct; it should be written as 2 + 2.
 The complete expression should be enclosed between ‘ ‘, called the backtick.
Arithmetic Operators
The following arithmetic operators are supported by Bourne Shell. Assume variable a holds
10 and variable b holds 20 then −

Operator Description Example

+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30

- (Subtraction) Subtracts right hand operand from left hand `expr $a - $b` will give -10
operand

* Multiplies values on either side of the `expr $a \* $b` will give 200
(Multiplication) operator

/ (Division) Divides left hand operand by right hand `expr $b / $a` will give 2
operand

% (Modulus) Divides left hand operand by right hand `expr $b % $a` will give 0
operand and returns remainder

= (Assignment) a = $b would assign value of


Assigns right operand in left operand
b into a

== (Equality) Compares two numbers, if both are same [ $a == $b ] would return


then returns true. false.

!= (Not Equality) Compares two numbers, if both are [ $a != $b ] would return


different then returns true. true.

It is very important to understand that all the conditional expressions should be inside square
braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is
incorrect.
All the arithmetical calculations are done using long integers.
8.1.9. Relational Operators
Bourne Shell supports the following relational operators that are specific to numeric
values. These operators do not work for string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well
as in between "10" and "20" but not in between "ten" and "twenty".

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


Assume variable a holds 10 and variable b holds 20 then –

Operator Description Example

-eq Checks if the value of two operands are equal or [ $a -eq $b ] is not true.
not; if yes, then the condition becomes true.

-ne Checks if the value of two operands are equal or


not; if values are not equal, then the condition [ $a -ne $b ] is true.
becomes true.

-gt Checks if the value of left operand is greater than


the value of right operand; if yes, then the [ $a -gt $b ] is not true.
condition becomes true.

-lt Checks if the value of left operand is less than the


value of right operand; if yes, then the condition [ $a -lt $b ] is true.
becomes true.

-ge Checks if the value of left operand is greater than


or equal to the value of right operand; if yes, then [ $a -ge $b ] is not true.
the condition becomes true.

-le Checks if the value of left operand is less than or


equal to the value of right operand; if yes, then [ $a -le $b ] is true.
the condition becomes true.

It is very important to understand that all the conditional expressions should be placed inside
square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <=
$b] is incorrect.
8.1.10. Boolean Operators
The following Boolean operators are supported by the Bourne Shell. Assume
variable a holds 10 and variable b holds 20 then −

Operator Description Example

! This is logical negation. This inverts a true


[ ! false ] is true.
condition into false and vice versa.

-o This is logical OR. If one of the operands is [ $a -lt 20 -o $b -gt 100 ] is true.
true, then the condition becomes true.

-a This is logical AND. If both the operands


are true, then the condition becomes true [ $a -lt 20 -a $b -gt 100 ] is false.
otherwise false.
8.1.11. String Operators
The following string operators are supported by Bourne Shell. Assume variable a holds
"abc" and variable b holds "efg" then –

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


Operator Description Example

= Checks if the value of two operands are [ $a = $b ] is not true.


equal or not; if yes, then the condition
becomes true.

!= Checks if the value of two operands are [ $a != $b ] is true.


equal or not; if values are not equal then the
condition becomes true.

-z Checks if the given string operand size is [ -z $a ] is not true.


zero; if it is zero length, then it returns true.

-n Checks if the given string operand size is non- [ -n $a ] is not false.


zero; if it is nonzero length, then it returns
true.

str Checks if str is not the empty string; if it is [ $a ] is not false.


empty, then it returns false.
8.1.12. File Test Operators
We have a few operators that can be used to test various properties associated with a Unix
file. Assume a variable file holds an existing file name "test" the size of which is 100 bytes
and has read, write and execute permission on –

Operator Description Example

-b file Checks if file is a block special file; if yes, then the [ -b $file ] is false.
condition becomes true.

-c file Checks if file is a character special file; if yes, then [ -c $file ] is false.
the condition becomes true.

-d file Checks if file is a directory; if yes, then the condition [ -d $file ] is not true.
becomes true.

-f file Checks if file is an ordinary file as opposed to a [ -f $file ] is true.


directory or special file; if yes, then the condition
becomes true.

-g file Checks if file has its set group ID (SGID) bit set; if yes, [ -g $file ] is false.
then the condition becomes true.

-k file Checks if file has its sticky bit set; if yes, then the [ -k $file ] is false.
condition becomes true.

-p file Checks if file is a named pipe; if yes, then the [ -p $file ] is false.
condition becomes true.

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


-t file Checks if file descriptor is open and associated with [ -t $file ] is false.
a terminal; if yes, then the condition becomes true.

-u file Checks if file has its Set User ID (SUID) bit set; if yes, [ -u $file ] is false.
then the condition becomes true.

-r file Checks if file is readable; if yes, then the condition [ -r $file ] is true.
becomes true.

-w file Checks if file is writable; if yes, then the condition [ -w $file ] is true.
becomes true.

-x file Checks if file is executable; if yes, then the condition [ -x $file ] is true.
becomes true.

-s file Checks if file has size greater than 0; if yes, then [ -s $file ] is true.
condition becomes true.

-e file Checks if file exists; is true even if file is a directory [ -e $file ] is true.
but exists.
8.2. Shell Decision Making
Unix Shell supports conditional statements which are used to perform different actions based
on different conditions. We will now understand two decision-making statements here −
 The if...else statement
 The case...esac statement
The if...else statements
If else statements are useful decision-making statements which can be used to select an
option from a given set of options.
Unix Shell supports following forms of if…else statement −
 if...fi statement
 if...else...fi statement
 if...elif...else...fi statement
Most of the if statements check relations using relational operators discussed in the previous
chapter.
The case...esac Statement
You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.
Unix Shell supports case...esac statement which handles exactly this situation, and it does so
more efficiently than repeated if...elif statements.
There is only one form of case...esac statement which has been described in detail here −

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


 case...esac statement
The case...esac statement in the Unix shell is very similar to the switch...case statement we
have in other programming languages like C or C++ and PERL, etc.
8.3. Shell Loop Types
A loop is a powerful programming tool that enables you to execute a set of commands
repeatedly. In this chapter, we will examine the following types of loops available to shell
programmers −
 The while loop
 The for loop
 The until loop
 The select loop
You will use different loops based on the situation. For example, the while loop executes the
given commands until the given condition remains true; the until loop executes until a given
condition becomes true.
Once you have good programming practice you will gain the expertise and thereby, start using
appropriate loop based on the situation. Here, while and for loops are available in most of the
other programming languages like C, C++ and PERL, etc.
Nesting Loops
All the loops support nesting concept which means you can put one loop inside another similar
one or different loops. This nesting can go up to unlimited number of times based on your
requirement.
Here is an example of nesting while loop. The other loops can be nested based on the
programming requirement in a similar way −
Nesting while Loops
It is possible to use a while loop as part of the body of another while loop.
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true

while command2 ; # this is loop2, the inner loop


do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true


done
Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop
that you used to count to nine −

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


#lab11.sh
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
This will produce the following result. It is important to note how echo -n works here. Here -
n option lets echo avoid printing a new line character.
8.4. Run a shell scrip
- After create a shell, save with a name (example: lab11.sh)
- $ chmod +x lab11.sh
- $ ./lab11.sh
- Result:
- 0
- 10
- 210
- 3210
- 43210
- 543210
- 6543210
- 76543210
- 876543210
- 9876543210
- $
8.5. Examples
8.5.1. Create a new script lab12.sh with the following content:
#!/bin/bash
greeting="Welcome"
user=$(whoami)
day=$(date +%A)
echo "$greeting back $user! Today is $day, which is the best day of the entire week!"
echo "Your Bash shell version is: $BASH_VERSION. Enjoy!"

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


- By now you should possess all required skills needed to create a new script, making it
executable and running it on the command line. After running the
above lab21.sh script, you will see an output similar to the one below:
- $ chmod +x lab21.sh
- $ ./lab21.sh
- Result:
Welcome back linuxconfig! Today is Wednesday, which is the best day of the entire
week! Your Bash shell version is: 4.4.12(1)-release. Enjoy!
8.5.2. Lab31.sh (backup.sh) script
#!/bin/bash
# This bash script is used to backup a user's home directory to /tmp/.
user=$(whoami)
input=/home/$user
output=/tmp/${user}_home_$(date +%Y-%m-%d_%H%M%S).tar.gz
tar -czf $output $input 2> /dev/null
echo "Backup of $input completed! Details about the output backup file:"
ls -l $output
Notes: when you want to exit, press: ctrl+D
8.5.3. Function (lab41.sh)
#!/bin/bash
# This bash script is used to backup a user's home directory to /tmp/.
user=$(whoami)
input=/home/$user
output=/tmp/${user}_home_$(date +%Y-%m-%d_%H%M%S).tar.gz
# The function total_files reports a total number of files for a given directory.
function total_files {
find $1 -type f | wc -l
}
# The function total_directories reports a total number of directories
# for a given directory.
function total_directories {
find $1 -type d | wc -l
}
tar -czf $output $input 2> /dev/null
echo -n "Files to be included:"
total_files $input
echo -n "Directories to be included:"
total_directories $input

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


echo "Backup of $input completed!"
echo "Details about the output backup file:"
ls -l $output
Result:$./lab41.sh
doan
Files to be included:6938
Directories to be included:447
Backup of /home/doan completed!
Details about the output backup file:
-rw-rw-r-- 1 doan doan 251601815 Th04 6 07:57 /tmp/doan_home_2023-04-
06_075709.tar.gz
9. Examples
9.1. Compare 2 numbers (lab51.sh)
we compare two integers using the nfumeric comparison operator to determine if
they are equal in value. Remember, 0 signals true, while 1 indicates false:
#!/bin/bash
string_a="UNIX"
string_b="GNU"
echo "Are $string_a and $string_b strings equal?"
[ $string_a = $string_b ]
echo $?
num_a=100
num_b=100
echo "Is $num_a equal to $num_b ?"
[ $num_a -eq $num_b ]
echo $?
 Save the above script as eg. lab51.sh (comparison.sh) file, make it executable
and execute:
 chmod +x lab51.sh
 $ ./lab51.sh
Are UNIX and GNU strings equal?
1
Is 100 equal to 100 ?
0
9.2. Conditional statement (lab61.sh)
#!/bin/bash
num_a=400
num_b=200
if [ $num_a -lt $num_b ]; then
echo "$num_a is less than $num_b!"
else
echo "$num_a is greater than $num_b!"

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


fi
9.3. For loop
#!/bin/bash
for i in 1 2 3; do
echo $i
done
9.4. While loop
#!/bin/bash
counter=0
while [ $counter -lt 3 ]; do
let counter+=1
echo $counter
done
9.5.
10.

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

You might also like