- Back to Home »
- Shell »
- Shell - Shell Functions
Sunday, July 12, 2015
1. Creating Functions
Syntax:
function_name () {
list of commands
}
Ex:
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World"
}
# Invoke your function
Hello
$./test.sh
Hello World
2. Pass Parameters to a Function
Việc pass parameters vào một function tương tự như đối với khi pass vào shell script.
Ex:
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali
$./test.sh
Hello World Zara Ali
3. Returning Values from Functions
Syntax:
function_name () {
list of commands
return code
}
Ex:
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali
# Capture value returnd by last command
ret=$?
echo "Return value is $ret"
$./test.sh
Hello World Zara Ali
Return value is 10
4. Nested Functions
Việc trong một hàm lại gọi một hàm con nữa cũng tương tự như trong lập trình C.
Ex:
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}
number_two () {
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
$./test.sh
This is the first function speaking...
This is now the second function speaking...
5. Function Call from Promp
Syntax:
$. test.sh
Với test.sh là shell script có chứa function.Ex:
$. test.sh
This is the first function speaking...
This is now the second function speaking...
$
$ number_one
This is the first function speaking...
This is now the second function speaking...
Khi muốn loại bỏ function:
Syntax:
$unset .f function_name