了解高级编程语言(C/C++、Java、PHP、Python、Perl 等)会向外行人建议 Bourne Again Shell (Bash) 函数应该像在其他语言中一样工作。
取而代之的是,Bash 函数的工作方式与 shell 命令类似,并期望将参数传递给它们,就像将选项传递给 shell 命令一样(例如 ls -l)。实际上,Bash 中的函数参数被视为位置参数($1, $2..$9, ${10}, ${11},等等)。考虑到getopts 的工作原理,这并不奇怪。不要使用括号来调用 Bash 中的函数。
(注意:我目前正在处理OpenSolaris。)
# Bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# In the actual shell script
# $0 $1 $2
backupWebRoot ~/public/www/ webSite.tar.zip
想要为变量使用名称?就这样做吧。
local filename=$1 # The keyword declare can be used, but local is semantically more specific.
不过要小心。如果函数的参数中有空格,您可能想要这样做!否则,$1 可能不是你想的那样。
local filename="$1" # Just to be on the safe side. Although, if $1 was an integer, then what? Is that even possible? Humm.
想要将数组按值传递给函数吗?
callingSomeFunction "${someArray[@]}" # Expands to all array elements.
在函数内部,像这样处理参数。
function callingSomeFunction ()
{
for value in "$@" # You want to use "$@" here, not "$*" !!!!!
do
:
done
}
需要传递一个值和一个数组,但在函数内部仍然使用“$@”?
function linearSearch ()
{
local myVar="$1"
shift 1 # Removes $1 from the parameter list
for value in "$@" # Represents the remaining parameters.
do
if [[ $value == $myVar ]]
then
echo -e "Found it!\t... after a while."
return 0
fi
done
return 1
}
linearSearch $someStringValue "${someArray[@]}"
在 Bash 4.3 及更高版本中,您可以通过使用 -n 选项定义函数的参数,通过引用将数组传递给函数。
function callingSomeFunction ()
{
local -n someArray=$1 # also ${1:?} to make the parameter mandatory.
for value in "${someArray[@]}" # Nice!
do
:
done
}
callingSomeFunction myArray # No $ in front of the argument. You pass by name, not expansion / value.