簡單的 bash 函式
井民全, Jing, mqjing@gmail.com
Show me the code
--------------------------------------------------------------------------------------
#!/bin/sh
die() {
echo "${0##*/}: error: $*" >&2
exit 1
}
usage() {
echo "Usage: foo [options] [args]
This does something useful!
Options:
-o Write output to
-v Run verbosely
-h This help screen"
exit 0
}
main() {
local flag
local verbose="false"
local out="/dev/stdout"
while getopts 'ho:v' flag; do
case ${flag} in
h) usage ;;
o) out="${OPTARG}" ;;
v) verbose="true" ;;
*) die "invalid option found" ;;
esac
done
if [[ ${verbose} == "true" ]]; then
echo "verbose mode is enabled!"
else
echo "will be quiet"
fi
if [[ -z ${out} ]]; then
die "-o flag is missing"
fi
echo "writing output to: '${out}'"
# Now remaining arguments are in "$@".
...
}
main "$@" # $@: 所有的參數
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Common
Use 0 for true and 1 for false
E.g.
# Defintion
function myfunc()
{ local myresult='some value' echo "$myresult" }
# Usage
result=$(myfunc) # or result=`myfunc`
echo $result |
Example 1: Simple Invoke
Function
function myfunc()
{ myresult='some value' } |
# Usage
myfunc
echo $myresult
myfunc
echo $myresult
Example 2: Simple Invoke
function GetRunningKernelVersion {
uname -r | cut -f1 -d'-'
}
|
# Usage
RunningKernelVersion=$(GetRunningKernelVersion)
Example 3:
# Function wget_checkproxy
# return
# 0: proxy enabled
# 1: proxy disabled
function wget_checkproxy(){
file=~/.wgetrc
x=`cat ${file} | grep use_proxy=yes`
#echo ${x}
if [[ ${x:0:1} == '#' ]]
then
return 1
else
return 0
fi
}
|
function wget_checkproxy_test(){
wget_checkproxy
if [ $? == 0 ]; then {
echo "wget proxy was enabled"
};fi
wget_checkproxy
if [ $? == 1 ]; then {
echo "wget proxy was disabled"
};fi
}
|
example 2
#Function LinkTest
#Arg
# ${1}: the nic name which you want to test
#Return
# 0: the nic was linked.
# 1: the nic was no linked.
#Usage
#ex 1:
# LinkTest eth0
#
#ex 2:
#if LinkTest eth0; then {
# echo "return 1"
#} else {
# echo "return others"
#};fi
#
#
#if LinkTest eth0 && LinkTest eth1; then {
# echo "check ok: eth0 and eth1 link ok"
#} else {
# echo "Please check your eth0 and eth1 conection correct"
# return 1;
#};fi
function LinkTest(){
local nic_ready=`sudo mii-tool | grep "link ok" | grep ${1}`
echo Test ${1} Status
if [ -n "${nic_ready}" ]; then {
echo "ok: ${1} linked "
return 0;
} else {
echo "fail: ${1} no link"
return 1;
};fi
}
|
Reference