Shell programming
What Is Kernel ?
• Kernel is heart of Linux Os.
• It manages resource of Linux Os.
• It decides who will use this resource, for how
long and when.
• The kernel acts as an intermediary between
the computer hardware and various
programs, application, shell.
1
Shell in a Linux system
User requests
Shell Application
Linux kernel
Hardware
What Is a Shell?
• A shell is a program that takes commands
typed by the user and calls the operating
system to run those commands.
• A shell is a program that acts as the interface
between you and the Linux system, allowing
you to enter commands for the operating
system to execute.
• Shell accepts your instruction or commands in
English and translate it into computers native
binary language
2
Why we use Shells?
• You can use shell scripts to automate
administrative tasks.
• Encapsulate complex configuration details.
• Get at the full power of the operating system.
• The ability to combine commands allows you to
create new commands
• Adding value to your operating system.
Kind of Shells
• Each of these shells has properties that make
them highly efficient for a specific type of use
over other shells
• Following are the most frequently used Shells
in Linux:
• The Bourne shell (sh)
• The Korn shell (ksh)
• The C shell (csh)
• Bourne Again Shell (bash).
• Bash is the default shell on many Linux
distributions today
3
Tip: To change your default Shell
• To find all available shells in your system type
following command:
• $ cat /etc/shells
• The basic Syntax :
• chsh username new_default_shell
• The administrator can change your default
shell.
Relationship among Shells
Korn shell Bourne Again Shell
C shell
Bourne shell
Common Common
core core
4
Shell functions
Shell functions
Built-in Scripts Variables Redirection Wildcards Pipes Sequence Subshells Background Command
Commands Processing subsitution
Local Environment Conditional Unconditional
How shell work?
Linux Converted to Binary
Your Command
Language By Shell
or Sell Script Shell
Now Linux Kernel
Understand
Your Request
5
Example
0100111001001
ls date BASH 1110011000111
cat file.txt 1111110111101
Linux Kernel
The Shell as a Programming Language
• Now that we’ve seen some basic shell
operations, it’s time to move on to scripts.
• There are two ways of writing shell programs.
1. You can type a sequence of commands and allow
the shell to execute them interactively.
2. You can store those commands in a file that you
can then invoke as a program(shell script).
6
Shell Scripting
• A shell script is similar to a batch file in MS-
DOS but is much more powerful.
• Shell script is a series of command(s) stored
in a plain text file.
Where shell scripting actively used?
• Monitoring your Linux system.
• Data backup and creating snapshots.
• Find out what processes are eating up your
system resources.
• Find out available and free memory.
• Find out all logged in users and what they are
doing.
• Find out if all necessary network services are
running or not.
•…
7
To create a shell script
• Use any text editor:
• vi, emacs, gedit
• The content of a shell script contains series of
commands
• If there are more commands on the same line, they
are separated by a semicolon “;”
• Setup executable permission
• chmod o+x file_name
• Execute a shell
• bash file_name
• sh file_name
• ./file_name
A simple shell script
• $vi first
# My first shell script
clear
echo "Hello $USER"
echo –e "Today is \c ";date
echo –e "Number of user login : \c" ; who | wc –l
echo "Calendar"
• $ chmod 755 first
• $./first
8
Variables in Shell
• In Linux (Shell), there are two types of
variable:
• System variables - Created and maintained by
Linux itself. This type of variable defined in
CAPITAL LETTERS.
• User defined variables (UDV) - Created and
maintained by user. This type of variable defined in
lower letters.
• Print or access value of UDV:
• $variable_name
• echo $HOME
• echo $USERNAME
You must use $ followed by variable name.
System variables
9
User defined variables (UDV)
• To define UDV use following syntax:
• variable name=value
• $ no=10
• Rules for Naming variable name
• Variable name must begin with Alphanumeric
character or underscore character (_), followed by
one or more Alphanumeric character.
• Don't put spaces on either side of the equal sign
when assigning value to variable.
• Variables are case-sensitive.
• You can define NULL variable
• Do not use ?,* etc, to name your variable names.
Example
10
Echo command
• Syntax:
echo [option] [string, variables…]
• To print some special characters with option -e:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash
• Example:
$ echo -e "An apple a day keeps away
\a\t\tdoctor\n"
Shell Arithmetic
• Syntax:
• expr op1 math-operator op2
• Examples:
• $ expr 1 + 3
• $ expr 2 – 1
• $ expr 10 / 2
• $ expr 20 % 3
• $ expr 10 \* 3
• $ echo `expr 6 + 3`
11
Quotation mark
• Double quotation mark“ ”
• All characters within double quotation mark are text
and can not be used for maths except \ or $
• Single quote ` (and ~)
• Can be used to execute a command
• Example:
$ echo “Today is `date`”
Today is Tue Jan …
Class work
• Write a shell script to print system variables
12
Return state
• Linux return:
• State 0 if the command ends successfully.
• State not zero if there was any error
• To check return state of a command
• $?
• Example
rm unknow1file
If there is no file named unknow1file, the system will give
a message:
rm: cannot remove `unkowm1file': No such file or directory
If execute following command:
$ echo $?
The return value will not be zero.
The read Statement
• Use to get input (data from user) from
keyboard and store (data) to variable.
• Syntax:
• read variable1, variable2,...variableN
13
Class work
• Write a shell script to make a sum. The name
of the script is add. The script acts as follows:
• $add
The first number: 12
The second number: 46
The sum: …
Command line parameters
• A shell script can take parameters from
command line
$myshell foo bar
• Reference:
• Command: $0
• Parameters: $1, $2…
• Order of parameter: $#
14
Class work
• Write a shell script get two parameters from
command line
• $add a b
• To make a sum a+b
• Write a shell script to print list of sub-directory
inside a given directory
• $subdir path
• list of sub-directory follows the path.
• Write a shell script to find a file in a folder (but
not in a sub-folder)
• $search path file_name
Exercise
• Write a shell script to print list of sub-directory
inside a given directory. The script name is
subdir.
• The script acts as follows:
$subdir path
Where path is the path to the directory in which
a list of sub-directory will be printed.
Note that do not print any file
15
if condition
• Syntax:
if condition then
command1 # if condition is true or if exit status of
condition is 0(zero)
fi
IF condition - example
• For example, a script named showfile has the
following content:
• Execute the script:
$./showfile foo
• $1 give the value of foo
16
Nested if-else-fi
• Syntax
if condition_1
then
command_1
….
else
command _2
fi
Test command
• Test command is used to check an
EXPRESSION is valid or not and return:
• 0 if the EXPRESSION is valid
• <>0, the other cases
• Syntax:
test EXPRESSION
[ EXPRESSION ]
• EXPRESSION can contain:
• Integer
• File
• String
17
Test command
• Maths
Test command
• String
18
Test command
• File and folder
Test command
• Logic operator:
• NOT: !
• ! EXPRESSION
• AND: -a
• EXPRESSION _1 –a EXPRESSION _2
• OR: -r
• EXPRESSION _1 –r EXPRESSION _2
19
Test command
• Example, file ispositive:
• $ ./ispositive 5
5 number is positive
For loop
• Syntax
for { variable name } in { list }
do
Các câu lệnh
done
Or:
for (( expr1; expr2; expr3 ))
do
Các câu lệnh
done
• Example, file testfor
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
for ((i=0; i<10; i++))
do
done
20
While loop
• Syntax
while [ condition ]
do
command1
command2
command3 .. ....
done
Exercise
• Write a shell script to execute like ls command,
however, the shell script will list sub-folder
before the file
• Write a shell script get the path to a file from
command line and check if the user has
permission rwx on the file or not
• Example: ./testrwx file_name
• Write a shell script filter a list of all files in a
folder where user has permission to read, write
and execute
• Example: ./listwrx path
21
The case Statement
• Syntax
case $variable-name in
pattern1) command
... ..
command;;
pattern2) command
... ..
command;;
patternN) command
... ..
command;;
*) command #default
... ..
command;;
esac
The case Statement
# if no vehicle name is given
# i.e. –z $1 is defined and it is NULL
# if no command line arg
if [ -z $1 ]
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then # otherwise make first arg as rental
rental=$1
fi
case $rental in
"car") echo "For $rental Rs.20 per k/m";;
"van") echo "For $rental Rs.10 per k/m";;
"jeep") echo "For $rental Rs.5 per k/m";;
"bicycle") echo "For $rental 20 paisa per k/m";;
*) echo "Sorry, I can not gat a $rental for you";;
esac
22
Exercise
• Write a shell script that get two numbers from
command line and return the bigger one.
• $max 23 54
• The max number is 54
• Write a shell script to check if a path exist or
not and check if it is a file or a folder.
• $file_data /etc/passwd1
File does not exist
• $file_data /etc/passwd
File exists and is a data file
• $file_data /etc
File exists and is a folder
Exercise 1
• Write a shell script to print lunar year of a given
year. The given year is given from command
line.
• Example:
• $lunar_year 2004
Giap Than
• $lunar_year 2007
Dinh hoi
- $lunar_year 2013
Quy ty
23
Exercise 1
• Lunar year has Can and Chi
• Can (10): Giáp, Ất, Bính, Đinh, Mậu, Kỷ, Canh, Tân,
Nhâm, Quý
• Chi (12): Tý, Sửu… Tuất, Hợi.
Each year of Can increase 1, Chi increase 1 compare
with the previous year
Known tha 2015 is Ất Mùi
$lunar_year 2013
Exercise 2
• Write a shell script to call lunar_year and print
years from 1990 to 2020 with the lunar year
name of them.
• Write a shell script print all things inside a
given folder. The path of the folder is given
from command line, the script is similar to ls
command, but it prints sub-folder before files.
24
Exercise 3
• Write a shell script called “nop_bai” as follows: Assume
that user log into the system by their username, i.e.,
tuananh:
• If user execute
• $nop_bai tep1 tep2
• The script copies files into the folder: /home/baitaplinux/tuananh.
• Only the owner can modify their files.
• User can view their uploaded files
• $nop_bai -l
• User can not view the others’ uploaded files including list of files and files’ content
• User can re-upload file and overwrite uploaded one
• The new file will overwrite the old one if they have the same name. The overwrite requests confirmation from
the user
• User can download their uploaded file to view the content.
• Each time the script is executed, its activity will be logged onto the file log.txt with
the following information: who executed, when it is executed, which command is
executed
• Other necessary function
25