You are on page 1of 38

Lp

trnh Shell

Trng Diu Linh


Lp trnh shell l g
Shell l trnh thng dch lnh ca Linux
Thng tng tc vi ngi dng theo tng cu
lnh.
Shell c lnh t bn phm hoc le
Nh ht nhn Linux thc hin lnh
Shell script
Cc chng trnh shell, bao gm chui cc lnh.

Son v thc thi chng trnh shell
S dng mi trnh son tho dng text:
vi, emacs, gedit
Ni dung bao gm cc cu lnh c s dng trn dng
lnh ca Linux
Cc cu lnh trn cng 1 dng phi phn tch bng du ;
Thit lp quyn thc thi cho chng trnh shell
chmod o+x ten_le
Thc thi
bash ten_le
sh ten_le
./ten_le


V d shell n gin
$vi rst
# 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 rst
$./rst
Bin trong shell
Trong Linux shell c 2 loi bin:
Bin h thng:
To ra v qun l bi Linux.
Tn bin l CH HOA
Bin do ngi dng nh ngha
To ra v qun l bi ngi dng
Tn bin l ch thng
Xem hoc truy nhp gi tr cc bin:
$tn_bin
echo $HOME
echo $USERNAME
Phi c du $ trc tn bin
divided into small locations, and each location had unique number called memory location/address,
which is used to hold our data. Programmer can give a unique name to this memory location/address
called memory variable or variable (Its a named storage location that may take different values, but only
one at a time).

Mt s bin h thng
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.
You can see system variables by giving command like $ set, some of the important System variables are:
System Variable Meaning
BASH=/bin/bash Our shell name
BASH_VERSION=1.14.7(1) Our shell version name
COLUMNS=80 No. of columns for our screen
HOME=/home/vivek Our home directory
LINES=25 No. of columns for our screen
LOGNAME=students students Our logging name
OSTYPE=Linux Our Os type
PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings
PS1=[\u@\h \W]\$ Our prompt settings
PWD=/home/students/Common Our current working directory
SHELL=/bin/bash Our shell name
USERNAME=vivek User name who is currently login to this PC

NOTE that Some of the above settings can be different in your PC/Linux environment. You can print any
of the above variables contains as follows:
$ echo $USERNAME
$ echo $HOME
Exercise:
1) If you want to print your home directory location then you give command:
nh ngha cc bin ca ngi dng
C php:
tn_bin=gi_tr
In gi tr ca bin
echo $tn_bin
V d:
no=10
echo $no

Quy tc t tn bin
Tn bin phi bt u bng k t
HOME
SYSTEM_VERSION
no
vech
Khng c du cch hai bn ton t = khi
gn gi tr cho bin
no=10 # l ng
no =10 # l sai
no = 10 #l sai
Quy tc t tn bin
Tn bin c phn bit ch hoa, thng
Cc bin sau y l khc nhau:
no=10
No=11
NO=20
nO=2
Mt bin khng c gi tr khi to th bng
NULL
Khng c dng du ?, * t tn cc bin
Exercise
Q.1.How to Define variable x with value 10 and print it on screen.

V d
Q.2.How to Define variable xn with value Rani and print it on screen
Q.3.How to print sum of two numbers, let's say 6 and 3?
Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
Q.5.Modify above and store division of x and y to variable called z
Q.6.Point out error if any in following script
$ vi variscript
#
#
# Script to test MY knowledge about variables!
#
myname=Vivek
myos = TroubleOS
myno=5
echo "My name is $myname"
echo "My os is $myos"
echo "My number is myno, can you see this number"
For Answers Click here

Prev Home
Lnh echo
C php:
echo [opon] [string, variables]
In mt s k t c bit trong tham s vi ty chn -e:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash
V d:
$ echo -e "An apple a day keeps away \a\t\tdoctor\n"


Cc php ton s hc
thc hin cc php nh ton s hc cn dng cu
lnh:
expr biu_thc_s_hc
Cc ton t: +, -, \*, /, %
V d:
expr 1 + 3
expr 2 - 1
expr 10 / 2
expr 20 % 3
expr 10 \* 3 # php nhn l \* .
echo `expr 6 + 3` # nh gi gi tr biu thc 6+3 v in ra.

Cc du ngoc
Du ngoc kp
Tt c cc k t trong du ngoc kp u khng c
ngha nh ton, tr nhng k t sau \ hoc $
Du nhy ngc ` (cng nt vi du ~)
Yu cu thc hin lnh
VD:
$ echo Today is `date`
Today is Tue Jan
Bi tp
Vit chng trnh in ra cc bin h thng
Trng thi kt thc cu lnh
Linux mc nh tr v:
Trng thi 0 nu cu lnh kt thc thnh cng.
Khc 0 nu kt thc c li
Kim tra trng thi kt thc mt cu lnh
$? : cho bit trng thi kt thc cu lnh trc
V d
rm unknow1le
Nu khng c le ny, h thng thng bo
rm: cannot remove `unkowm1le': No such le or directory
Nu thc hin lnh:
$ echo $?
S in ra gi tr khc 0.

LSST v1.05r3 > Chapter 2 > The read Statement

Linux Shell Scripting Tutorial (LSST) v1.05r3


Prev Chapter 2: Getting started with Shell Programming

Cu lnh c d liu u vo
The read Statement
c d liu t bn phm v ghi vo bin
Use to get input (data from user) from keyboard and store (data) to variable.
Syntax:
read variable1, variable2,...variableN
C php:
Following script first ask user, name and then waits to enter name from the user via keyboard.
enters name from keyboard (after giving name you have to press ENTER key) and entered nam
read variable1
keyboard is stored (assigned) to variable fname.
$ vi sayH
#
#Script to read your name from key-board
#
echo "Your first name please:"
read fname
echo "Hello $fname, Lets be friend!"
Run it as follows:
$ chmod 755 sayH
$ ./sayH
Your first name please: vivek
Hello vivek, Lets be friend!

Prev Home
Wild cards (Filename Shorthan
command which file you would like to rem
command by specifying filename. Also you
more users friendly. But how we access co
Cc tham s dng lnh
Lets take ls command
$ Ls -a /*
This command has 2 command line argum
Mt chng trnh shell c th c cc tham s
$ myshell foo bar
dng lnh
$myshell foo bar
Tham chiu:
tn lnh: $0
cc tham s: $1, $2
S cc tham s: $#
Shell Script name i.e. myshell

First command line argument passed

Second command line argument passe


Bi tp
Vit chng trnh add a b
Chng trnh thc hin a+b
Vit chng trnh hin th danh sch cc th
mc con ca mt th mc
$subdir path
Lit k cc th mc con nm trong path.
Vit chng trnh m kim 1 tp trong 1 th
mc (nhng khng trong th mc con)
$search path tn_tp
Bi kim tra
Vit chng trnh shell thc hin chc nng
hin th danh sch cc th mc con ca mt
th mc. Chng trnh t tn l subdir.
Chng trnh c chy nh sau
$subdir path
Trong path l ng dn n th mc s
c lit k th mc con.
Ch : khng lit k cc le
Cu trc r nhnh if
C php:
if iu_kin
then
cu lnh 1

fi
Cu lnh 1 c thc hin khi iu_kin l ng
hoc trng thi kt thc ca iu_kin l 0 (kt
thc thnh cng).
Cu trc r nhnh if
LSST v1.05r3 > Chapter 3 > if condition
V d, tp showle c ni dung:
$ cat > showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi
Thc thi tp:
Run above script as:
$./showle foo
$ chmod 755 showfile
$./showfile foo
$1 cho gi tr foo
Shell script name is showfile ($0) and foo is argument (which is $1).Then shell compare
if cat $1 which is expanded to if cat foo.
Detailed explanation
if cat command finds foo file and if its successfully shown on screen, it means our cat co
Cu trc r nhnh if else
C php
if iu_kin
then
cu_lnh_1
.
else
cu_lnh_2

Lnh test
Lnh test c dng kim tra mt biu thc l
ng hay khng v tr li
0 nu biu thc ng
<>0, trng hp cn li
C php:
test biu_thc
[ biu thc ]
Biu thc c th bao gm:
S nguyn
Cc kiu p
Xu k t
Lnh test
Cc php ton kim tra
LSST v1.05r3 > Chapter 3 > test command or [ expr ]

For Mathematics, use following operator in Shell Script


Mathematical Normal Arithmetical/
Operator in Shell Meaning Mathematical But in Shell
Script Statements
For test For [ expr ]
statement with statement with
if command if command
-eq is equal to 5 == 6 if test 5 -eq 6 if [ 5 -eq 6 ]
-ne is not equal to 5 != 6 if test 5 -ne 6 if [ 5 -ne 6 ]
-lt is less than 5<6 if test 5 -lt 6 if [ 5 -lt 6 ]
is less than or
-le 5 <= 6 if test 5 -le 6 if [ 5 -le 6 ]
equal to
-gt is greater than 5>6 if test 5 -gt 6 if [ 5 -gt 6 ]
is greater than
-ge 5 >= 6 if test 5 -ge 6 if [ 5 -ge 6 ]
or equal to

NOTE: == is equal, != is not equal.


For string Comparisons use
Operator Meaning
-lt is less than 5<6 if test 5 -lt 6 if [
is less than or
-le 5 <= 6 if test 5 -le 6 if [
equal to
-gt
-ge
Lnh test
is greater than
is greater than
5 >= 6
5>6 if test 5 -gt 6
if test 5 -ge 6
if [
if [
or equal to

Cc php so snh xu
NOTE: == is equal, != is not equal.
For string Comparisons use
Operator Meaning
string1 = string2 string1 is equal to string2
string1 != string2 string1 is NOT equal to string2
string1 string1 is NOT NULL or not defined
-n string1 string1 is NOT NULL and does exist
-z string1 string1 is NULL and does exist

Shell also test for file and directory types


Test Meaning
-s file Non empty file
-f file Is File exist or normal file and not a directory
-d dir Is Directory exist and not a file
-w file Is writeable file
For string Comparisons use
Operator Meaning
string1 = string2 string1 is equal to string2

string1
Lnh test
string1 != string2 string1 is NOT equal to string2
string1 is NOT NULL or not defined
-n string1 string1 is NOT NULL and does exist
-zCc php kim tra le, th mc
string1 string1 is NULL and does exist

Shell also test for file and directory types


Test Meaning
-s file Non empty file
-f file Is File exist or normal file and not a directory
-d dir Is Directory exist and not a file
-w file Is writeable file
-r file Is read-only file
-x file Is file is executable

Logical Operators
Logical operators are used to combine two or more condition at a time
Operator Meaning
! expression Logical NOT
Lnh test
Cc php ton logic:
NOT: !
! Biu_thc
AND: -a
Biu_thc_1 a biu_thc_2
OR: -r
Biu thc_1 r biu_thc_2
test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0
returns nonzero for false.
Syntax:
Lnh test
test expression OR [ expression ]

Example:
V d tp isposive:
Following script determine whether given argument number is positive.
$ cat > ispositive
#!/bin/sh
#
# Script to see whether argument is positive
#
if test $1 -gt 0
then
echo "$1 number is positive"
fi

$ ./isposive 5
Run it as follows
$ chmod 755 ispostive
5 number is posi-ve
$ ispostive 5
5 number is positive
$ispostive -45
Nothing is printed
$ispostive
Cu trc lp for
C php
for { variable name } in { list }
do
Cc cu lnh
done
Hoc:
for (( expr1; expr2; expr3 ))
do
Cc cu lnh
done
V d tp testfor
for i in 1 2 3 4 5
do
echo "Welcome $i mes"
done
Syntax:

while [ condition ]
do

Cu trc lp while
command1
command2
command3
..
....
C php done
while [ condion ] Loop is executed as long as given condition is true. For e.g.. Above for loop program (shown in last
do section of for loop) can be written using while loop as:
command1
$cat > nt1
command2 #!/bin/sh
command3 .. .... #
done #Script to test while statement
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo " Use to print multiplication table for given number"
exit 1
fi
n=$1
i=1
while [ $i -le 10 ]
do
echo "$n * $i = `expr $i \* $n`"
i=`expr $i + 1`
done
Save it and try as
$ chmod 755 nt1
$./nt1 7
Bi tp
Vit mt chng trnh thc hin chc nng ca
lnh ls, tuy th lnh mi s lit k cc th mc
con trc ri mi n cc tp
Vit 1 chng trnh nhn ng dn n 1 tp t
dng lnh v kim tra ngi chy chng trnh
c quyn rwx trn tp khng
VD: ./testrwx tp
Vit 1 chng trnh lc danh sch cc tp nm
trong th mc path m ngi chy chng trnh
c quyn c, ghi, thc thi
VD: ./listwrx path
Cu trc case
C php
case $variable-name in
pa3ern1) command
... ..
command;;
pa3ern2) command
... ..
command;;
pa3ernN) command
... ..
command;;
*) command #default
... ..
command;;
esac
Cu trc case
# if no vehicle name is given
# i.e. z $1 is dened and it is NULL
#
# if no command line arg
if [ -z $1 ]
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make rst arg as rental
rental=$1

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
Bi tp 1
Vit chng trnh cho bit tn nm m lch ca
mt nm dng lch cho trc. Yu cu chng
trnh nhn nm dng lch ti dng lnh.
V d:
$lunar_year 2004
Giap Than
$lunar_year 2007
Dinh hoi
- $lunar_year 2013
Quy ty
Bi tp 1
Nm m lch gm Can v Chi
Can (10): Gip, t, Bnh, inh, Mu, K, Canh, Tn,
Nhm, Qu
Chi (12): T, Su Tut, Hi.
Mi nm Can tng thm 1, Chi tng thm 1 so vi
nm trc
Bit l 2015 l t Mi
$lunar_year 2013
Bi tp 2
Vit chng trnh gi chng trnh lunar_year
v in ra bng cc nm dng lch t 1990 n
2020 v tn nm m lch ca chng

Vit chng trnh lit k ni dung ca mt th
mc (c nhp vo t dng lnh), ging lnh
ls nhng lit k cc th mc con trc, cc
tp sau.

Bi tp
To chng trnh np bi nop_bai hot ng nh sau
Khi ngi dng ng nhp vo h thng vi tn ngi
dng, v d l tuananh, chng trnh cho php:
Nu ngi dng chy
$nop_bai tep1 tep2
Chng trnh copy cc tp vo th mc: ~/baitaplinux.
Chng trnh lu nht k thao tc vo le ~/baitaplinux/log.txt
Tuananh 12:30 04-1-2015 nop_bai tep1 tep2
Bi tp 3
To chng trnh np bi nop_bai hot ng nh sau
Khi ngi dng ng nhp vo h thng vi tn ngi
dng, v d l tuananh, chng trnh cho php:
Nu ngi dng chy
$nop_bai tep1 tep2
Chng trnh copy cc tp vo th mc: /home/baitaplinux.
Ngi dng ny khng sa c bi ca ngi dng kia.
Ngi dng c th xem li danh sch cc bi m mnh np v thng n
Ngoi dng khng th xem c cc bi np ca ngi dng khc (c
danh sch v ni dung)
Ngi dng c th np li bn mi (xa bn c)
Ngi dng c th ly li bi ca mnh v xem li ni dung.
Ghi nht k vo le log.txt cc ln chng trnh nop_bai c chy: ai
chy, ngy gi no, cu lnh g
Chng trnh c th c chc nng khc m bn thy cn thit.

You might also like