Upload
van-nghia-tran
View
235
Download
0
Embed Size (px)
Citation preview
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
1/46
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
2/46
2
Mc ch
Nm c cch s dng hm
Hiu v s dng cu trc mng Hiu c mt s v d minh ha
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
3/46
3
Ni dung
Vit khi lnh
Khai bo v s dng hm (Function) Khai bo v s dng mng Mt s v d v Linux Shell
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
4/46
4
S dng cp {} bc khi lnh : if [ -f file_one ] && {
ls -1echo complex block execute }then
#echo command completed fi
Khi lnh { . . . }
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
5/46
5
Shell cung cpcho NSD t tohm hay th tc triu gibntrong script.
C php nh nghahm : c 2 cchCch 1: function_name() {
statements
}
Cch 2: function function_name {
statements...
}
Khai bo v s dng hm (Function)
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
6/46
Khai bo v s dng hm (Function)
#!/bin/bashJUST_A_SECOND=1funky (){
echo "This is a simple function."echo "Now exiting simple function."
}
6
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
7/46
Khai bo v s dng hm (Function)
fun (){ i=0
REPEATS=30echoecho "And now the fun really begins."echosleep $JUST_A_SECOND # Hey, wait a second!
while [ $i lt $REPEATS ] do
echo " let "i+=1"
done}Funky # Now, call the functions.Fun # Now, call the functions.exit 07
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
8/46
Khai bo v s dng hm (Function)
tr v mt gi tr s ta c th dng lnh return : Vd : sum1() {
return 5}
tr v gi tr chui ta c th dng lnh echo : Vd : #!/bin/shsample_func() {
x=5echo Insight sample_func!
}echo Goi su dung ham sample_func
echo $xsample_func
# y=$(sample_func)exit 08
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
9/46
Khai bo v s dng hm (Function)
Binton cc v bin cc b khai bo bin cc b c hiu lc trong hm,
dng t kha local . Nu khng c t kha local, cc bin c
xem l binton cc. Bin ton cc c nhn thyv c th thay i
bi tt c cc hm trong script.
9
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
10/46
Khai bo v s dng hm (Function)
#!/bin/shsample_text=glocal variable fun1() {
local sample_text=local variable echo function fun1 is executing echo $sample_text
}echo $sample_textfun1echo script ended echo $sample_textexit 0
10
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
11/46
Khai bo v s dng hm (Function)
Hm v cch truyntham s Truyn tham s cho hm tng t nh
truyntham s trn dng lnh. Vd :
function1() "param1","param2","param3". . .
Bn trong hm s dng cc bin mitrng: $*, $1, $2 ly gi tr cc thams truynvo
11
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
12/46
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
13/46
Khai bo v s dng hm (Function)
max2 33 34return_val=$?if [ "$return_val" eq $E_PARAM_ERR ]then
echo "Need to pass two parameters to the function."elif [ "$return_val" eq $EQUAL ]
thenecho "The two numbers are equal."
elseecho "The larger of the two numbers is
$return_val."fiexit 0
13
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
14/46
Khai bo v s dng hm (Function)
VD: S dng bin ton cc v cc b (local)#!/bin/bash# Global and local variables inside a function.func()
{local loc_var=23 # Declared as local variable.echo # Uses the 'local' builtin.echo "\"loc_var\" in function = $loc_var"global_var=999 # Not declared as local.
# Defaults to global.echo "\"global_var\" in function = $global_var"
}
14
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
15/46
Khai bo v s dng hm (Function)
func# Now,to see if local variable "loc_var"# exists outsidefunction.echoecho "\"loc_var\" outside function = $ loc_var # $loc_var outside function =# No, $loc_var not visible globally.echo "\"global_var\" outside function = $ global_var # $global_var outside function = 999# $global_var is visible globally.echoexit 0
15
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
16/46
Khai bo v s dng mng
Phin bn mi ca Bash h tr mng 1 chiu. Mt phn t ca mng c khai bo v khi to nh sau:variable[xx]=values
lygi tr ca 1 phn t trong mng th s dng cu trc sau:
${variable[xx]}
16
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
17/46
Khai bo v s dng mng
khai bo 1 mng gi tr, ta s dng cu trcsau:
Cch 1: (c ch s mng l tun t) array=( zero one two three four five )
Cch 2: (gn ch s mng l c th) array_name=( [0]="first element" [1]="second
element [3]="fourth element" )
17
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
18/46
Khai bo v s dng mng
Vd1: Khai bo v dng mng n gin #!/bin/bash
area[11]=23area[13]=37
area[51]=UFOsecho -n "area[11] = "echo ${area[11]} # {curly brackets} needed.echo -n "area[13] = "echo ${area[13]}
echo "Contents of area[51] are ${area[51]}. echo -n "area[43] = "echo ${area[43]} (null variable).
18
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
19/46
Khai bo v s dng mng
# Sum of two array variables assigned to third area[5]=`expr ${area[11]} + ${area[13]}`echo "area[5] = area[11] + area[13]"echo -n "area[5] = "echo ${area[5]}area[6]=`expr ${area[11]} + ${area[51]}`echo "area[6] = area[11] + area[51]"echo -n "area[6] = "echo ${area[6]}# This fails because adding an integer to a
string is not permitted.exit 0
19
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
20/46
Khai bo v s dng mng
Bash cho php thc hin thao tc truy cp mng trn cc bin khngkhai bo kiu mng.
string=abcABC123ABCabcecho ${string[@]} # abcABC123ABCabc
echo ${string[*]} # abcABC123ABCabcecho ${string[0]} # abcABC123ABCabcecho ${string[1]} # No output!
# Why?echo ${#string[@]} # 1
# One element in the array.# The string itself.
20
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
21/46
Khai bo v s dng mng
# Lines of the text.Line[1]="I do not know which to prefer,"Line[2]="The beauty of inflections"
Line[3]="Or the beauty of innuendoes,"Line[4]="The blackbird whistling"Line[5]="Or just after. for index in 1 2 3 4 5 # Five lines.
doecho -n "${Line[index]}"
done21
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
22/46
MT S V D
V LINUX SHELL
22
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
23/46
1. X l chui
Tr v di ca chui (String Length) C php: 3 cch
${#string} expr length $string expr "$string" : '.*
V d
stringZ=abcABC123ABCabcecho ${#stringZ} # 15echo `expr length $stringZ` # 15echo `expr "$stringZ" : '.*'` # 15
23
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
24/46
1. X l chui
Tm di ca chui con khp vi chui string. C php: 2 cch
expr match "$string" '$substring'$substring is a regular expression.
expr "$string" : '$substring'$substring is a regular expression.
V d: stringZ=abcABC123ABCabc
#|| echo `expr match "$stringZ" 'abc[AZ]*.2` # 8 echo `expr "$stringZ" : 'abc[AZ]*.2'` # 8
24
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
25/46
1. X l chui
Ly ch s Index ca substring xut hin u tintrong string C php:
expr index $string $substring V d:
stringZ=abcABC123ABCabcecho `expr index "$stringZ" C12` # 6
# C position.echo `expr index "$stringZ" 1c` # 3# 'c' (in #3 position) matches before '1.
25
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
26/46
1. X l chui
Ly 1 chui con t 1 chui c sn Cp php
${string:position}Nu position l "*" hoc "@ th s ly ton b chui string.
${string:position:length} V d: stringZ=abcABC123ABCabc# 0123456789.....# 0based indexing. echo ${stringZ:0} # abcABC123ABCabcecho ${stringZ:1} # bcABC123ABCabcecho ${stringZ:7} # 23ABCabcecho ${stringZ:7:3} # 23A
26
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
27/46
1. X l chui
Loi b chui con trong chui string C php:
${string#substring} loi b chui con ngn nht trong chui string. Substring l biu thc chnh
qui
${string##substring} loi b chui con di nht trong chui string.
V d:stringZ=abcABC123ABCabc
# || # ||
echo ${stringZ#a*C} # 123ABCabc# Strip out shortest match between 'a' and 'C'.echo ${stringZ##a*C} # abc# Strip out longest match between 'a' and 'C'.
27
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
28/46
1. X l chui
Thay th chui C php ${string/substring/replacement} thay th chui con u tin khp vi substring. ${string//substring/replacement}
thay th ton b chui con khp vi substring V d:
stringZ=abcABC123ABCabcecho ${stringZ/abc/xyz} # xyzABC123ABCabc# Replaces first match of 'abc' with 'xyz'.echo ${stringZ//abc/xyz} # xyzABC123ABCxyz
# Replaces all matches of 'abc' with # 'xyz'.
28
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
29/46
2. S dng cc bin tham s
Vi d: your_id=${USER}on${HOSTNAME}
echo "$your_id"
echo "Old \$PATH = $PATH"PATH=${PATH}:/opt/bin #Add /opt/bin to$PATH for duration of script.
echo "New \$PATH = $PATH"
29
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
30/46
3. S dng declare
Phin bn Bash 2 hoc mi hn, h thng h tr tnhnng qui nh kiu cho bin. s dng chc nng ny, ta kho s cc tham s ty chn sau
r readonlydeclare r var1(declare r var1 works the same as readonly var1)
readonly variable fails with an error message.
30
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
31/46
3. S dng declare
i integer declare i number # The script will treat subsequent occurrences of "number" as an integer.number=3echo "Number = $number" # Number = 3
number=threeecho "Number = $number" # Number = 0# Tries to evaluate the string "three" as an integer.Certain arithmetic operations are permitted for declared integer variables without the
need for expr or let.n=6/3
echo "n = $n" # n = 6/3declare i n n=6/3echo "n = $n" # n = 2
31
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
32/46
3. S dng declare
a array declare a indices The variable indices will be treated as an array.
f function(s)
declare f function_name A declare f function_name in a script lists just the function named.
32
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
33/46
3. S dng declare
#!/bin/bashdeclare f # Lists the function above. echodeclare i var1 # var1 is an integer. var1=2367echo "var1 declared as $var1"var1=var1+1 # Integer declaration eliminates the need for 'let'.echo "var1 incremented by 1 is $var1."# Attempt to change variable declared as integer.echo "Attempting to change var1 to floating point value, 2367.1."var1=2367.1 # Results in error message, with no change to variable.echo "var1 is still $var1"echodeclare r var2=13.36 # 'declare' permits setting a variable property
#+ and simultaneously assigning it a value.echo "var2 declared as $var2" # Attempt to change readonly variable.var2=13.37 # Generates error message, and exit from script.echo "var2 is still $var2" # This line will not execute.exit 0 # Script will not exit here.
33
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
34/46
4. Tham chiu gin tip 1 bin
Assume that the value of a variable is the name of a second variable. Is it somehow possible toretrieve the
value of this second variable from the first one? For example, if a=letter_of_alphabet andletter_of_alphabet=z, can a reference to a return z?This can indeed be done, and it is called anindirect reference. It uses the unusual evalvar1=\$$var2 notation.
34
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
35/46
4. Tham chiu gin tip 1 bin . Indirect References#!/bin/bash# indref.sh: Indirect variable referencing. # Accessing the contents of the contents of a variable.a=letter_of_alphabet # Variable "a" holds the name of another variable.letter_of_alphabet=zecho# Direct reference.echo "a = $a" # a = letter_of_alphabet# Indirect reference.eval a=\$$aecho "Now a = $a" # Now a = z
echo# Now, let's try changing the secondorder reference. t=table_cell_3table_cell_3=24echo "\"table_cell_3\" = $table_cell_3" # "table_cell_3" = 24echo n "dereferenced \"t\" = "; eval echo \$$t # dereferenced "t" = 24# In this simple case, the following also works (why?).# eval t=\$$t; echo "\"t\" = $t"echot=table_cell_3NEW_VAL=387table_cell_3=$NEW_VALecho "Changing value of \"table_cell_3\" to $NEW_VAL."echo "\"table_cell_3\" now $table_cell_3"echo n "dereferenced \"t\" now "; eval echo \$$t# "eval" takes the two arguments "echo" and " \$$t" (set equal to $table_cell_3)echo# (Thanks, Stephane Chazelas, for clearing up the above behavior.)# Another method is the ${!t} notation, discussed in "Bash, version 2" section.# See also ex78.sh.exit 0
35
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
36/46
5. Hm $RANDOM: pht sinh integer
$RANDOM : in the range 0 32767. #!/bin/bash# $RANDOM returns a different random integer at each invocation.# Nominal range: 0 32767 (signed 16bit integer). MAXCOUNT=10count=1
echoecho "$MAXCOUNT random numbers:"echo "" while [ "$count" le $MAXCOUNT ] # Generate 10 ($MAXCOUNT) random integers. do
number=$RANDOMecho $number let "count += 1" # Increment count.
doneecho "" # If you need a random int within a certain range, use the 'modulo' operator.# This returns the remainder of a division operation.exit 0
36
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
37/46
5. Hm $RANDOM: pht sinh integer
#!/bin/bash# pickcard.sh # This is an example of choosing random
elements of an array.# Pick a card, any card.Suites="ClubsDiamonds
HeartsSpades"
37
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
38/46
5. Hm $RANDOM: pht sinh integer
Denominations="2345678910JackQueenKingAce"# Note variables spread over multiple lines.38
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
39/46
5. Hm $RANDOM: pht sinh integer
suite=($Suites) # Read into array variable.denomination=($Denominations)num_suites=${#suite[*]} # Count how many elements.num_denominations=${#denomination[*]}
echo n"${denomination[$((RANDOM%num_denominations))]} of"
echo ${suite[$((RANDOM%num_suites))]}exit 0
39
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
40/46
Summary
Khai bo v s dng hm (Function) Khai bo v s dng mng
Mt s v d v Linux Shell
40
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
41/46
Summary
41
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
42/46
Summary
42
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
43/46
Summary
43
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
44/46
Summary
44
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
45/46
Summary
45
7/30/2019 Chuong 3 - Bai 3_ham_vd_mau
46/46
46
Kt thc