You are on page 1of 18

SHELL---_LINUX

Phn 1 : Getting started with Shell Programming 1. Vit shell script nh th no ? Bc 1 : dng bt c chng trnh g c th son tho . V d : vi Bc 2 : sau khi vit xong phi gn quyn thc thi cho script V d : $ chmod +x tn script $ chmod 755 tn script Bc 3 : thc thi script C php : bash tn script sh tn script ./ tn script Cu trc mt chng trnh shell script nh sau : #!/bin/bash command command exit 0 shell m script s chy lnh thot

Ch : lnh exit 0 s c m t k trong phn Exit status 2. Bin trong shell Trong linux shell th c 2 kiu bin : Bin h thng (system variable) : c to bi Linux. Kiu bin ny thng c vit bng k t in hoa. Bin do ngi dng nh ngha. nh ngha bin : C php : tn bin=gi tr Mt s quy nh v bin trong shell : (1) Tn bt u bng k t hoc du gch chn (_). (2) Khng c c khong trng trc v sau du bng khi gn gi tr cho bin (3) Bin c phn bit ch hoa ch thng (4) Bn c th khai bo mt bin c gi tr NULL nh sau : var01= hoc var01= (5) Khng dng ?, * t tn bin. 3. S dng bin truy xut gi tr bin, dng c php sau : $tn_bin v d : n=10 echo $n 4. Lnh echo Dng hin th dng vn bn, gi tr bin C php : echo [options] [chui, bin] Cc option : -n : khng in k t xung dng. -e : cho php hiu nhng k t theo sau du \ trong chui \a : alert (ting chung) \b : backspace \c : khng xung dng \n : xung dng \r : v u dng \t : tab \\ : du \ v d : echo e mt hai ba \a\t\t bn \n

SHELL_LINUX

1-18

SHELL---_LINUX

5. Tnh ton trong Shell S dung expr C php : expr op1 php ton op2 V d : expr 1 + 3 expr 2 1 expr 10 / 2 expr 20 % 3 expr 10 \* 3 echo `expr 6 + 3` z=`epxr $z + 3` S dung let Vi du : let z=$z+3 let z += 3 let z=$m*$n S dung $((...)) vi du : z=$((z+3)) z=$(($m*$n)) ch : epxr 20 % 3 : 20 mod 3 epxr 10 \* 3 : php ton nhn , s dng \* ch khng phi * phn bit vi k t thay th. Dng cui trong v d trn c s dng rt nhiu trong shell, khi mt lnh c t gia 2 du `` (khng phi du nhy n ) th shell s thc thi lnh . V d : a=`epxr 10 \* 3` a s c gi tr l 10 x 3 = 30 in kt qu ra mn hnh : echo $a 6. Mt vi thng tin v du ngoc kp C 3 loi du sau : Du ` Tn Nhy kp Nhy n Nhy ngc ngha bt c g nm trong dy nhy kp c xem l nhng k t ring bit nhng g nm trong du nhy n c ngha khng i thc thi lnh

V d : echo hm nay l date khng in c hm nay l th my echo hm nay l `date` s in ra ngy thng hm nay v date nm trong du nhy ngc ` ` 7. Trng thi Exit Mc nh trong Linux, khi mt lnh hoc script thc thi , n tr v 2 loI gi tr xc nh xem lnh hoc script c thc thi thnh cng khng. (1). Nu gi tr tr v l 0 (zero) lnh thc thi thnh cng (2). Nu gi tr tr v khc 0 (nonzero) khng thnh cng Gi tr gI l Exit status Vy lm th no bit c gi tr tr v ca mt lnh hay 1 script ? Rt n gin, ch cn s dng bin c bit c sn ca shell : $? V d : nu bn xo 1 file khng tn tI trn a cng # rm unknowfile # echo $? s in ra mn hnh mt gi tr khc 0 8. Lnh read c gi tr nhp t bn phm , file Dng ly d liu nhp t bn phm v lu vo bin

SHELL_LINUX

2-18

SHELL---_LINUX

C php : read var1 var2 var3 varN read khng c tham s gi tr s c cha trong bin $REPLY v d : read var=$REPLY Bnh thng th du \ cho php xung dng nhp tip d liu trong read. Nu read r th s khng c ngha . V d : # read var # nhp vo : first line \ second line # echo $var kt qu : first line second line Nhng vI tham s r th sao ? # read r var # nhp vo : first line \ # echo $var kt qu : first line \ Lnh read c th dng c file. Nu file cha nhiu hn 1 dng th ch c dng th nht c gn cho bin . Nu read vI nhiu hn 1 bin (read var1 var2 ) th read s da vo bin $IFS gn d liu cho cc bin. Mc nh th $IFS l khong trng. V d : # read var < data_file Nu file c nhiu hn 1 dng # read var1 var2 < data_file Khi , mI bin s cha 1 chuI c cch bit bI khong trng ($IFS) ch khng phI 1 dng, bin cuI cng s c cha ton b phn cn lI ca dng. Vy lm th no c ton b file ? C th giI quyt bng vng lp khng ?? while read line do echo $line done < data_file S dng $IFS (Internal File Separator ) tch mt dng input ca read, nu bn khng mun mc nh l khong trng th lm nh th no ? Xem on script sau : echo liet ke tat ca user OIFS=$IFS; IFS=: # backup lI IFS v gn gi tr mi. V file /etc/passwd dng : tch bit # cc trng vI nhau nn gn IFS l : while read name passwd uid gid fullname ignore do echo $name $fullname done < /etc/passwd # I/O redirection IFS=$OIFS # tr lI IFS ban u Nu t IFS ngay trong vng lp th khng cn backup IFS while IFS=: read name passwd uid gid fullname ignore do echo $name $fullname done < /etc/passwd IFS vn khng i 9. Tham s lnh

SHELL_LINUX

3-18

SHELL---_LINUX

Gi s ta c script tn myself , thc thi script ny ta cn truyn vo 2 tham s nh sau : $ myself one two Trong myself l tn script one : tham s th nht truyn vo script two : tham s th hai Trong shell, bn truy xut n nhng tham s nh sau : myself l $0 one l $1 two l $2 V bin $# (c sn trong shell) s cho gi tr 2 (c 2 tham s one v two). Bn c th ly tt c cc tham s bng cch s dng bin $@ hoc $*

10.Redirection
V d :

Hu ht tt c lnh u cho xut kt qu ra mn hnh hoc ly d liu t bn phm nhng vI Linux bn cn c th xut d liu vo file v c d liu t file.

ls > filename # in kt qu lnh ls vo file c tn filename. C 3 k hiu redirection l >, >> v < (1). K hiu > c php : linux-command > filename Xut output ca lnh ra file. Nu file tn tI th n s ghi cn nu file cha c th to file mI (2). K hiu >> c php : linux-command >> filename Xut output ca lnh vo cuI file nu file tn tI, cn nu file cha tn tI th to file mi. (3). K hiu < c php : linux-command < filename ly d liu cho linux-command t filename thay v t bn fm. 11. Pipe C php : command 1 | command 2 Output ca command 1 s l d liu vo ca command 2 V d : $who | grep root

Phn 2 : Cu truc Shell

1.

True/False : Gia tri shell Zero ( 0 ) Non-zero Y nghia Yes/True No/False Vi du 0 -1, 32, 55 ... bt ky s nao khac 0

2.

iu kin if : Cu phap : if condition then command command

SHELL_LINUX

4-18

SHELL---_LINUX
fi ... Trong o : condition la true hoc exit status cua lnh la 0 (zero) thi thc hin command Vi du : gia s a co file tn la foo $ cat foo $ echo $? # $? La ly exit status cua lnh cat nu lnh cat tra v 0 ( zero ) thanh cng . shell script c vit nh sau : #!/bin/bash if cat $1 then echo e \n File $1 , tim thy va in ra thanh cng fi exit 0 3. Lnh test hay cu truc [ biu thc ] Lnh test hoc cu truc [ biu thc ] dung kim tra 1 biu thc la ung hay sai, nu ung tra v 0, ngc lai la s khac 0 Cu phap : test biu thc HOC [ biu thc ] Vi du : Test biu thc If test $1 gt 0 Then echo $1 ln hn 0 fi Biu thc kim tra lam vic vi : (1). S nguyn (2). Nhng kiu file (3). Chui Toan t trong shell script -eq -ne -lt -le -gt -ge So sanh chui Toan t string1 = string2 string1 != string2 String -n string -z string Kim tra file va th muc Test -s file -f file -d dir -w file Y nghia File khng rng File tn tai. La file , khng phai th muc Th muc tn tai , khng phai file. File ghi c Y nghia String 1 bng string 2 String 1 khng bng string 2 String cha inh nghia String khng NULL String NULL Y nghia S hoc Lnh test 5 test 5 test 5 test 5 test 5 test 5 If trong shell test eq 6 ne 6 lt 6 le 6 gt 6 ge 6 [ biu thc ] [5 eq 6 ] [ 5 ne 6 ] [ 5 lt 6 ] [ 5 le 6 ] [ 5 gt 6 ] [ 5 ge 6 ] [ biu thc ] if [ $1 gt 0 ] then echo $1 ln hn 0 fi

So sanh bng Khng bng Nho hn Nho hn hay bng Ln hn Ln hn hoc bng

5 == 6 5!=6 5<6 5<=6 5>6 5>=6

If If If If If If

If If If If If If

SHELL_LINUX

5-18

SHELL---_LINUX
-r file -x file

File chi oc File co quyn thc thi

Toan t logic Toan t ! expr1 a epxr2 expr1 o epxr2 4. if .else.fi Cu phap if iu kin then Y nghia NOT AND OR

iu kin la zero (true - 0) thc thi tt ca lnh phia trn else nu iiu kin khng ung ( non-zero) thc thi tt ca lnh trn fi

else fi

Cu truc if lng nhau Cu phap : if iu kin 1 then thc thi lnh nu iu kin 1 ung else if iu kin 2 then thc thi lnh khi iu kin 2 ung else thc thi lnh khi iu kin 2 khng ung fi fi Vi du osch=0 echo "1. Unix (Sun Os)" echo "2. Linux (Red Hat)" echo -n "Select your os choice [1 or 2]? " read osch if [ $osch -eq 1 ] ; then echo "You Pick up Unix (Sun Os)" else #### nested if i.e. if within if ###### if [ $osch -eq 2 ] ; then echo "You Pick up Linux (Red Hat)" else echo "What you don't like Unix/Linux OS." fi

fi 5. Multilevel if-then-else Cu phap :

SHELL_LINUX

6-18

SHELL---_LINUX

if iu kin 1 then iu kin 1 ung thc thi cac lnh trn elif elif iu kin 2 then iu kin 2 ung (true - 0) thc thi cac lnh trn elif elif iu kin 3 then iu kin 3 ung (true - 0) thc thi cac lnh trn elif else khng co iu kin nao trn ung thc thi cac lnh trn fi fi

Vi du : #!/bin/sh # Script to test if..elif...else if [ $1 -gt 0 ]; then echo "$1 is positive" elif [ $1 -lt 0 ] then echo "$1 is negative" elif [ $1 -eq 0 ] then echo "$1 is zero" else echo "Opps! $1 is not number, give number" fi 6. Vng lp trong shell script: Vng lp for C php : for { bin } in { danh sch } do lnh lnh done v d : for i in 1 2 3 4 5 do echo "Welcome $i times" done Vng lp for cng c th c vit ging c php C nh sau : for (( biu thc 1; biu thc 2; biu thc 3 )) do lnh lnh done V d : do for (( i = 0 ; i <= 5; i++ ))

SHELL_LINUX

7-18

SHELL---_LINUX
done

echo "Welcome $i times"

Vng lp for lng nhau for (( i = 1; i <= 5; i++ )) do ### Outer for loop ###

for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ### do echo -n "$i " done echo "" #### print the new line ### done 7. Vng lp while C php while [ iu kin ] do command1 command2 command3 .. .... done V d #!/bin/sh # #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 8. Cu trc case C php case $variable-name in pattern1) command ... .. command;; pattern2) command ... ..

SHELL_LINUX

8-18

SHELL---_LINUX
patternN)

*)

esac

command;; command ... .. command;; command ... .. command;;

Ch : cuI mI pattern u phI c du ;; *) s thc hin khi tt c cc trng hp u khng ng. 9. Lm sao debug script ? Mc nh th bash khng c cng c debug c th no ngoi nhng thng bo lI c php n gin . Nhng thng ip cng khng gip c g cho vic tm lI phc tp. V d : #!/bin/bash # ex74.sh # This is a buggy script. # Where, oh where is the error? a=37 if [$a -gt 27 ] then echo $a fi exit 0 Khi chy script ny, n s thng bo ./ex74.sh: [37: command not found Nhn vo y chng ta bit rng script trn b lI dng 37 (ngay sau if) V d : #!/bin/bash # missing-keyword.sh: What error message will this generate? for a in 1 2 3 do echo "$a" # done # Required keyword 'done' commented out in line 7. exit 0 Thng bo lI : missing-keyword.sh: line 10: syntax error: unexpected end of file Ch rng thng bo lI khng phI lun lun ch ra ng dng b lI m l dng khi trnh bin dch pht hin ra li.

SHELL_LINUX

9-18

SHELL---_LINUX

V d : on code trn, bash s khng thng bo lI dng s 7 m l thng bo lI cuI file v n dng s 10 , bash mI pht hin ra l thiu t kho kt thc vng lp. Mt s ch debug nhng script khng chy :

Dng lnh echo bit c gi tr bin tI ni m ta cho l b li. S dng lnh tee kim tra d liu tI ni b lI s dng cc option ca sh, bash : -n , -v , -x sh n scriptname : kim tra lI c php (khng chy script). Tng ng vI vic chn vo script lnh : set n hoc set o noexec sh v scriptname : in ra mI dng lnh trc khi chy n. Tng ng chn vo script lnh : set v hoc set o verbose Cc option n, -v cng lm vic cng nhau , bn c th g lnh sh nv scriptname sh x scriptname : in ra kt qu mI lnh theo lI vit tt. N tng ng bn chn vo script lnh : set x hoc set o xtrace S dng trap kim tra signal lc exit. Nu s dng phng php ny th lnh trap phI l lnh u tin ca script. C php : trap { command } { signal } Signal 0 1 2 3 9 V d : #!/bin/bash trap 'echo Variable Listing --- a = $a b = $b' EXIT (0) # EXIT l tn ca signal pht sinh khi thot khI script. a=39 b=36 exit 0 Phn 3. Bash script nng cao Khi xy ra Thot khI shell Hangup Interup (Ctrl+C) Quit Kill

1.

Conditional execution ( && and ||) Cu phap cho &&: command1 && command2 Command2 thc thi nu command 1 tra v exit status la zero (true) Cu phap cho || command1 || command2 Command 2 chi thc thi khi exit status cua command 1 la khac 0 (false) Co th s dung ca hai : command1 && command2 || command3 Nu command 1 thanh cng thi thc thi command2, nu khng thi thc thi command3

SHELL_LINUX

10-18

10

SHELL---_LINUX

Vi du : $ rm myf && echo xoa thanh cong || echo chua xoa duoc file

2. I/O Redirection and file descriptors I/O redirector dung gi output cua lnh ra file va oc input t file. Vi du : $ cat > myf this is my file nhn Ctrl+D cat se tao file myf cha dong this is my file Trong lp trinh Linux, cac thit bi nh ban phim, man hinh ... u c coi nh la cac tp tin co tn nh sau : Standard File Stdin Stdout Stderr File descriptor number 0 1 2 S dung Standard input Standard output Standard error Vi du Ban phim Man hinh Man hinh

Chung ta a kha quen thuc vi stdin va stdout. File cui cung trong bang trn la stderr (s 2) c chng trinh dung in li ra man hinh. Ta co th redirect output t 1 file descriptor ra file vi cu phap sau : $ File-descriptor-number > filename Vi du : gia s file aaa.txt khng tn tai $ rm aaa.txt rm: cannot remove `bad_file_name111': No such file or directory Cu lnh trn se thng bao li khng co file. By gi chung ta hay redirec li nay ra file . $ rm aaa.txt > er Lnh vn in li ra man hinh va ni dung file er khng co gi ht. Vy lam sao output li ra file ?? Hay th lnh sau : $ rm aaa.txt 2>er Chu y rng khng c co khoang trng gia 2 va > (2>er). Vi du : if [ $# -ne 2 ] then echo "Error : Number are not supplied" 1>&2 echo "Usage : $0 number1 number2" 1>&2 exit 1 fi ans=`expr $1 + $2` echo "Sum is $ans" 1>&2 cui lnh echo se redirect t standard output n standard error. Cu phap : from>&destination 3. Ham Cu phap : function-name ( ) { command1 ..... ... commandN return } hoc function function-name

SHELL_LINUX

11-18

11

SHELL---_LINUX
{ command1 ..... ... commandN return

Trong o, function-name la tn ham, lnh return se kt thuc ham. Goi ham : function-name Truyn tham s : function-name $arg1 $arg2 Ly tham s truyn vao ham : arg1=$1; arg2=$2 Ly gia tri tra v cua ham : Nu ham return v mt gia tri nao o thi sau khi goi ham , gia tri return se cha trong bin $?

4. User Interface Tao menu tng tac vi ngi dung. #!/bin/bash while : do clear echo "---------------------------------------" echo " Main Menu" echo "---------------------------------------" echo "[1] Show today date/time" echo "[2] Show all files in current directory" echo "[3] Show calendar" echo "[4] Exit/Stop" echo "=======================" echo -n "Enter your choice [1-4]: " read choice case $choice in 1) echo "Today is `date` " echo "Press Enter key to continue ..."; read;; 2) echo "Files in $PWD"; ls -l echo "Press Enter key to continue..."; read;; 3) cal ; echo "Press Enter key to continue..."; read;; 4) exit 0;; *) echo "Please choice 1,2,3,4. Press Enter key to continue..."; read;; esac done 5. Lnh Shift Shift di chuyn nhng tham s command line qua trai 1 vi tri. Vi du : $ myfile -f foo bar $1 = -f ; $2 = foo ; $3 = bar khi goi lnh shift thi gia tri cac bin se nh sau : $1 = foo ; $2 = bar ; Ta co th di chuyn qua trai nhiu hn 1 vi tri bng cach thm s vao sau lnh shift Vi du : shift 2

6.

Phat sinh s ngu nhin $RANDOM la 1 bin ham cua Bash (khng phai la hng s) cho phep phat sinh s ngu nhin trong pham vi 0 32767 vi du :

SHELL_LINUX

12-18

12

SHELL---_LINUX
#!/bin/bash MAXCOUNT=10 count=1 echo echo "$MAXCOUNT random numbers:" echo "-----------------" while [ "$count" -le $MAXCOUNT ] # Generate 10 ($MAXCOUNT) random integers. do number=$RANDOM echo $number let "count += 1" # Increment count. done exit 0 7. Mang : array[xx] Co th khai bao mang bng lnh declare a array Ly gia tri mang : ${array[xx]} ${array[@]} hoc ${array[*]} : ly tt ca phn t cua mang ${#array[@]} hoc ${#array[*]} : tng s phn t cua mang Xoa mang : dung lnh unset Vi du : unset array[1] : xoa phn t th 2 cua mang array unset array : xoa toan b mang Vi du : array[5]=`expr ${array[11]} + ${array[13]}` Cach khac : array=( zero one two three four ) array[0]=zero ; array[4]=four Cach khac : Array=( [xx]=XXX [yy]=YYY ...) Array=([17]=seventeen [21]=twenty-one) Vi du : array=( zero one two three four five ) echo ${array[0]} echo ${array:0} echo ${array:1} echo ${#array[0]} echo ${#array} echo ${#array[1]} echo ${#array[*]} echo ${#array[@]} # zero # zero # ero : ly t vi tri s 1 cua phn t th nht # 4 : chiu dai cua phn t th nht # 4 # 3 : chiu dai cua phn t th 2 # 6 : s phn t cua mang # 6 : s phn t cua mang.

Vi du : array2=( [0]="first element" [1]="second element" [3]="fourth element" ) echo echo echo echo ${array2[0]} ${array2[1]} ${array2[2]} ${array2[3]} # # # # first element second element khng khi tao nn co gia tri null fourth element

SHELL_LINUX

13-18

13

SHELL---_LINUX
Vi du : arrayZ=( one two three four five five ) echo ${arrayZ[@]:0} # one two three four five five : tt ca cac phn t echo ${arrayZ[@]:1} # two three four five five : ly t phn t th 1 echo ${arrayZ[@]:1:2} # two three : ly phn t 1 n 2 Vi du : khai bao mang rng array0=( first second third ) array1=( ' ' ) # "array1" co 1 phn t rng. array2=( ) # mang rng Vi du : ni rng mang ( khai bao thm phn t vao mang ) array0=( "${array0[@]}" "new1" ) # ${array0[@]} la toan b mang cu, new1 la phn t mi array1=( "${array1[@]}" "new1" ) array2=( "${array2[@]}" "new1" ) hoc array0[${#array0[*]}]="new2" array1[${#array1[*]}]="new2" array2[${#array2[*]}]="new2" Vi du : chep mang array2=( "${array1[@]}" ) hoc array2="${array1[@]}" 8. X ly chui Chiu dai chui : ${#string} hoc expr length $string Vi du : stringZ=abcABC123ABCabc echo ${#stringZ} # 15 echo `expr length $stringZ` # 15 echo `expr "$stringZ" : '.*'` # 15 Index : expr index $string $substring Vi du : stringZ=abcABC123ABCabc echo `expr index "$stringZ" C12` echo `expr index "$stringZ" 1c` # 6 : C vi tri C # 3 : vi tri c hoc expr "$string" : '.*'

Chui con : ${string:position} Ly chui con cua chui string bt u t position ${string:position:length} ly length ky t t vi tri position Vi du : stringZ=abcABC123ABCabc # 0123456789..... index tinh t 0

SHELL_LINUX

14-18

14

SHELL---_LINUX

echo ${stringZ:0} echo ${stringZ:1} echo ${stringZ:7} echo ${stringZ:7:3}

# abcABC123ABCabc # bcABC123ABCabc # 23ABCabc # 23A : ly 3 ky t t vi tri 7

Co th ly index t cui chui khng ? echo ${stringZ:-4} # Khng hoat ng #Tuy nhin ....... # abcABC123ABCabc

echo ${stringZ:(-4)} # Cabc echo ${stringZ: -4} # Cabc # chu y : position trong ngoc n hoc co khoang trng sau du : thi no se lam vic. Cach khac : expr substr $string $position $length Ly length ky t cua chui string t vi tri position Vi du : stringZ=abcABC123ABCabc # 123456789......

Index tinh t 1 # ab # ABC

echo `expr substr $stringZ 1 2` echo `expr substr $stringZ 4 3` Xoa chui con

${string#substring} xoa chui substring ngn nht tinh t u chui khoi chui string ${string##substring} xoa chui substring dai nht tinh t u chui khoi chui string

Vi du : stringZ=abcABC123ABCabc # |------| # |---------------| echo ${stringZ#a*C} echo ${stringZ##a*C} # 123ABCabc # abc

${string%substring} va ${string%%substring} ging nh trn nhng tinh t cui chui Vi du : stringZ=abcABC123ABCabc # || # |-----------------| echo ${stringZ%b*c} echo ${stringZ%%b*c} # abcABC123ABCa #a

Thay th chui ${string/substring/replacement} thay th chui trung vi substring bng replacement ( trung ln u tin ) ${string//substring/replacement} thay th tt ca chui trung vi substring bng replacement Vi du : stringZ=abcABC123ABCabc echo ${stringZ/abc/xyz} echo ${stringZ//abc/xyz} # xyzABC123ABCabc # xyzABC123ABCxyz

SHELL_LINUX

15-18

15

SHELL---_LINUX
Bai tp Bai 1 : Vit chng trinh shell giai phng trinh bc hai : ax2 + bx +c =0 vi cac tham s a,b,c nhp t ban phim va cac kt qua chinh xac n hai ch s. #!/bin/bash echo -n "a= " read a echo -n "b= " read b echo -n "c= " read c delta=$(echo "$b^2 - 4*$a*$c" | bc) if [ $delta -lt 0 ] then echo "pt vo nghiem" elif [ "$delta" -eq 0 ] then echo -n "pt co nghiem kep x= " x=$(echo "scale=2; -$b/(2*$a)" | bc) echo "$x" else echo "phuong trinh co 2 nghiem" x1=$(echo "scale=2; -($b + sqrt($delta))/(2*$a)" | bc) echo "x1= $x1" x2=$(echo "scale=2; -($b - sqrt($delta))/(2*$a)" | bc) echo "x2= $x2" fi exit 0

Bai 2 : Vit chng trinh shell lit k cac tp tin trong th muc nhp vao t ban phim ma co kich thc > 4KB theo dang sau : Tng s tp tin Tp tin 1 kich thc ..... tp in n kich thc #!/bin/bash SIZE=4096 # hng s echo -n "thu muc : " read directory index=0 for file in $( find $directory -type f) do filesize=$(ls -l $file | awk '{print $5}') if [ $filesize -gt $SIZE ] then _filename[$index]=$file _filesize[$index]=$filesize let "index +=1" fi

# trng th 5 cua kt qua lnh ls l la kich # thc file # gan mang file name # gan mang file size

SHELL_LINUX

16-18

16

SHELL---_LINUX

Edited by Foxit Reader Copyright(C) by Foxit Corporation,2005-2010 For Evaluation Only.

done echo "Tong so tap tin : $index" for ((i=0 ; i<index; i++)) do echo -e "`basename ${_filename[i]}`\t\t kich thuoc: ${_filesize[i]}" done exit 0 Bai 3 : Vit chng trinh shell oc mt danh sach cac user t tp tin users ri kim tra xem cac user nay co thuc group sinhvien hay khng? Nu co user nao thuc group thi xoa user o ra khoi group sinhvien ngc lai thi thm user o vao group. #!/bin/bash FGROUP=/etc/group GROUPNAME=sinhvien UFILE=users if [ ! -e $UFILE ]; then echo "File users does not exist" exit 1 fi all_users=( $(cat $FGROUP | grep -w $GROUPNAME | cut -d: -f4 | tr , " ") ) # all_users=( $(cat $FGROUP | awk F: /$GROUPNAME/ {print $4} | tr , " ") ) num_usr_grp=${#all_users[@]} add_remove_users(){ local co=0 for (( i=0; i< num_usr_grp; i++ )) do if [ "$1" == "${all_users[i]}" ] then co=1;break fi done if [ $co -eq 1 ]; then gpasswd -d $1 $GROUPNAME else gpasswd -a $1 $GROUPNAME fi

while read usr do add_remove_users $usr done <$UFILE exit 0 Bai 4 Vit chng trinh i 1 s t h thp phn 10 ( Dec ) sang h 2 (Bin), 8 (Oct) , 16 (Hex). Vi du : convert b 16 n 500 co nghia la i s 500 sang c s 16. Chu y : oan code di y cung dung minh hoa lnh shift . Ban co th go tham s cua chng trinh theo 2 cach : ./convert b radix n number hoc ./conver n number b radix #!/bin/bash

SHELL_LINUX

17-18

17

SHELL---_LINUX
if [ $# -ne 4 ]; then echo "Usage : $0 -b radix -n number or $0 -n number -b radix" exit 1 fi while [ "$1" ] do if [ "$1" = "-b" ];then ob="$2" case $ob in 16 ) basesystem="Hex";; 8 ) basesystem="Oct";; 2 ) basesystem="Bin";; * ) basesystem="Unknown";; esac shift 2 elif [ "$1" = "-n" ] then num="$2" shift 2 else echo "Program $0 does not recognize option $1" exit 1 fi done op=$(echo "obase=$ob;ibase=10;$num;" | bc) echo "$num Decimal number = $op in $basesystem number system (base=$ob)" exit 0 oan code trn thi quan trong nht la dong op=$(echo "obase=$ob;ibase=10;$num;" | bc). Lnh nay dung chuyn c s. ------ End----

SHELL_LINUX

18-18

18

You might also like