LậptrìnhShell
TrươngDiệuLinh
Lậptrìnhshelllàgì
• ShelllàtrìnhthôngdịchlệnhcủaLinux
– Thườngtươngtácvớingườidùngtheotừngcâu
lệnh.
– Shellđọclệnhtừbànphímhoặcfile
– NhờhạtnhânLinuxthựchiệnlệnh
• Shellscript
– Cácchươngtrìnhshell,baogồmchuỗicáclệnh.
Soạnvàthựcthichươngtrìnhshell
• Sửdụngmọitrìnhsoạnthảodạngtext:
– vi,emacs,gedit
– Nộidungbaogồmcáccâulệnhđượcsửdụngtrêndòng
lệnhcủaLinux
– Cáccâulệnhtrêncùng1dòngphảiphântáchbằngdấu;
• Thiếtlậpquyềnthựcthichochươngtrìnhshell
– chmodo+xten_file
• Thựcthi
– bashten_file
– shten_file
– ./ten_file
Vídụshellđơngiản
• $vifirst
# 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"
• $chmod755first
• $./first
Biếntrongshell
• TrongLinuxshellcó2loạibiến:
– Biếnhệthống:
• TạoravàquảnlýbởiLinux.
• TênbiếnlàCHỮHOA
– Biếndongườidùngđịnhnghĩa
• Tạoravàquảnlýbởingườidùng
• Tênbiếnlàchữthường
– Xemhoặctruynhậpgiátrịcácbiến:
• $tên_biến
• echo$HOME
• echo$USERNAME
Phảicódấu$trướctênbiến
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).
Mộtsốbiếnhệthống
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
BASH=/bin/bash
Meaning
Our shell name
BASH_VERSION=1.14.7(1)
COLUMNS=80
HOME=/home/vivek
LINES=25
LOGNAME=students
OSTYPE=Linux
PATH=/usr/bin:/sbin:/bin:/usr/sbin
PS1=[\u@\h \W]\$
PWD=/home/students/Common
SHELL=/bin/bash
USERNAME=vivek
Our shell version name
No. of columns for our screen
Our home directory
No. of columns for our screen
students Our logging name
Our Os type
Our path settings
Our prompt settings
Our current working directory
Our shell name
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:
Địnhnghĩacácbiếncủangườidùng
• Cúpháp:
tên_biến=giá_trị
• Ingiátrịcủabiến
echo$tên_biến
• Vídụ:
no=10
echo$no
Quytắcđặttênbiến
• Tênbiếnphảibắtđầubằngkýtự
– HOME
– SYSTEM_VERSION
– no
– vech
• Khôngđượcđểdấucáchhaibêntoántử=khi
gángiátrịchobiến
no=10#làđúng
no=10#làsai
no=10#làsai
Quytắcđặttênbiến
• Tênbiếncóphânbiệtchữhoa,thường
– Cácbiếnsauđâylàkhácnhau:
no=10
No=11
NO=20
nO=2
• Mộtbiếnkhôngcógiátrịkhởitạothìbằng
NULL
• Khôngđượcdùngdấu?,*đểđặttêncácbiến
Exercise
Q.1.How to Define variable x with value 10 and print it on screen.
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
Vídụ
$ 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
Lệnhecho
• Cúpháp:
echo[opŒon][string,variables…]
• Inmộtsốkýtựđặcbiệttrongthamsốvớitùychọn-e:
\aalert(bell)
\bbackspace
\csuppresstrailingnewline
\nnewline
\rcarriagereturn
\thorizontaltab
\\backslash
• Vídụ:
$echo-e"Anappleadaykeepsaway\a\t\tdoctor\n"
Cácphéptoánsốhọc
• Đểthựchiệncácphép–nhtoánsốhọccầndùngcâu
lệnh:
exprbiểu_thức_số_học
Cáctoántử:+,-,\*,/,%
• Vídụ:
expr1+3
expr2-1
expr10/2
expr20%3
expr10\*3#phépnhânlà\*.
echo`expr6+3`#đánhgiágiátrịbiểuthức6+3vàinra.
Cácdấungoặc
• Dấungoặckép“ ”
– Tấtcảcáckýtựtrongdấungoặcképđềukhôngcó
ýnghĩa–nhtoán,trừnhữngkýtựsau\hoặc$
• Dấunháyngược`(cùngnútvớidấu~)
– Yêucầuthựchiệnlệnh
VD:
$echo“Todayis`date`”
TodayisTueJan…
Bàitập
• Viếtchươngtrìnhinracácbiếnhệthống
Trạngtháikếtthúccâulệnh
• Linuxmặcđịnhtrảvề:
– Trạngthái0nếucâulệnhkếtthúcthànhcông.
– Khác0nếukếtthúccólỗi
• Kiểmtratrạngtháikếtthúcmộtcâulệnh
– $?:chobiếttrạngtháikếtthúccâulệnhtrướcđó
• Vídụ
rmunknow1file
Nếukhôngcófilenày,hệthốngthôngbáo
rm:cannotremove`unkowm1file':Nosuchfileordirectory
Nếuthựchiệnlệnh:
$echo$?
Sẽinragiátrịkhác0.
LSST v1.05r3 > Chapter 2 > The read Statement
Prev
Linux Shell Scripting Tutorial (LSST) v1.05r3
Chapter 2: Getting started with Shell Programming
Câulệnhđọcdữliệuđầuvào
The read Statement
• Đọcdữliệutừbànphímvàghivàobiến
• Cúpháp:
Following script first ask user, name and then waits to enter name from the user via keyboard.
Use to get input (data from user) from keyboard and store (data) to variable.
Syntax:
read variable1, variable2,...variableN
enters name from keyboard (after giving name you have to press ENTER key) and entered nam
readvariable1
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
Cácthamsốdònglệnh
Lets take ls command
•
$ Ls -a /*
This command has 2 command line argum
Mộtchươngtrìnhshellcóthểcócácthamsố
$ myshell foo bar
dònglệnh
$myshellfoobar
• Thamchiếu:
– tênlệnh:$0
– cácthamsố:$1,$2…
– Sốcácthamsố:$#
Shell Script name i.e. myshell
First command line argument passed
Second command line argument passe
Bàitập
• Viếtchươngtrìnhaddab
– Chươngtrìnhthựchiệna+b
• Viếtchươngtrìnhhiểnthịdanhsáchcácthư
mụcconcủamộtthưmục
– $subdirpath
– Liệtkêcácthưmụcconnằmtrongpath.
• Viếtchươngtrình£mkiếm1tệptrong1thư
mục(nhưngkhôngtrongthưmụccon)
– $searchpathtên_tệp
Bàikiểmtra
• Viếtchươngtrìnhshellthựchiệnchứcnăng
hiểnthịdanhsáchcácthưmụcconcủamột
thưmục.Chươngtrìnhđặttênlàsubdir.
Chươngtrìnhđượcchạynhưsau
$subdirpath
Trongđópathlàđườngdẫnđếnthưmụcsẽ
đượcliệtkêthưmụccon.
Chúý:khôngliệtkêcácfile
Cấutrúcrẽnhánhif
• Cúpháp:
if điều_kiện
then
câu lệnh 1
…
fi
Câulệnh1đượcthựchiệnkhiđiều_kiệnlàđúng
hoặctrạngtháikếtthúccủađiều_kiệnlà0(kết
thúcthànhcông).
Cấutrúcrẽnhánhif
LSST v1.05r3 > Chapter 3 > if condition
Vídụ,tệpshowfilecónộidung:
$• cat
> showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi
• Thựcthitệp:
Run
above script as:
$ chmod
755 showfile
$./showfilefoo
$./showfile
foo
• $1chogiá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
Cấutrúcrẽnhánhif…else…fi
• Cúpháp
ifđiều_kiện
then
câu_lệnh_1
….
else
câu_lệnh_2
fi
Lệnhtest
• Lệnhtestđượcdùngđểkiểmtramộtbiểuthứclà
đúnghaykhôngvàtrảlại
– 0nếubiểuthứcđúng
– <>0,trườnghợpcònlại
• Cúpháp:
testbiểu_thức
[biểuthức]
• Biểuthứccóthểbaogồm:
– Sốnguyên
– CáckiểuŒệp
– Xâukýtự
Lệnhtest
• Cácphéptoánkiểmtra
LSST v1.05r3 > Chapter 3 > test command or [ expr ]
For Mathematics, use following operator in Shell Script
Mathematical
Operator in Shell
Script
-eq
-ne
-lt
Meaning
is equal to
is not equal to
is less than
is less than or
equal to
is greater than
is greater than
or equal to
-le
-gt
-ge
Normal Arithmetical/
Mathematical
Statements
5 == 6
5 != 6
5<6
For test
For [ expr ]
statement with statement with
if command
if command
if test 5 -eq 6
if [ 5 -eq 6 ]
if test 5 -ne 6
if [ 5 -ne 6 ]
if test 5 -lt 6
if [ 5 -lt 6 ]
5 <= 6
if test 5 -le 6
if [ 5 -le 6 ]
5>6
if test 5 -gt 6
if [ 5 -gt 6 ]
5 >= 6
if test 5 -ge 6
if [ 5 -ge 6 ]
NOTE: == is equal, != is not equal.
For string Comparisons use
Operator
But in Shell
Meaning
-lt
is less than
is less than or
equal to
is greater than
is greater than
or equal to
-le
-gt
-ge
5<6
if test 5 -lt 6
if [
5 <= 6
if test 5 -le 6
if [
Lệnhtest
5 >= 6
if test 5 -gt 6
if [
if test 5 -ge 6
if [
5>6
== is equal, != is not equal.
• NOTE:
Cácphépsosánhxâu
For string Comparisons use
Operator
string1 = string2
string1 != string2
string1
-n string1
-z string1
Meaning
string1 is equal to string2
string1 is NOT equal to string2
string1 is NOT NULL or not defined
string1 is NOT NULL and does exist
string1 is NULL and does exist
Shell also test for file and directory types
Test
-s file
-f file
-d dir
-w file
Meaning
Non empty file
Is File exist or normal file and not a directory
Is Directory exist and not a file
Is writeable file