我正试图搜索如何在Bash函数中传递参数,但找到的总是如何从命令行传递参数。
我想在我的脚本中传递参数。我试过了。
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
但语法不正确,如何向我的函数传递参数?
有两种典型的方法来声明一个函数。我更喜欢第二种方法。
function function_name {
command...
}
或
function_name () {
command...
}
调用一个带参数的函数。
function_name "$arg1" "$arg2"
该函数通过参数的位置(而不是名称)来指代传递的参数,也就是1美元、2美元,等等。$0是脚本本身的名称。
例子。
function_name () {
echo "Parameter #1 is $1"
}
另外,你需要在函数声明后***调用它。
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
输出:
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
对高级编程语言(C/C++/Java/PHP/Python/Perl...)的了解会让外行人认为bash函数应该像在其他语言中那样工作。相反,bash函数像shell命令一样工作,并且期望参数被传递给它们,就像人们向shell命令传递一个选项一样(ls -l)。实际上,bash中的函数参数被视为位置参数("$1, $2...$9, ${10}, ${11}",等等)。考虑到 "getopts "的工作方式,这并不奇怪。在bash中调用一个函数不需要括号。
(注:我现在正好在Open Solaris上工作。)
# 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
如果你喜欢命名参数,那么可以(通过一些技巧)将命名参数传递给函数(也可以传递数组和引用)。
我开发的方法可以让你定义命名参数,像这样传递给函数。
function example { args : string firstName , string lastName , integer age } {
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}
您也可以将参数注释为@required或@readonly,创建...其余参数,从顺序参数中创建数组(例如使用
string[4]
),并可以选择将参数列在多行中。
function example {
args
: @required string firstName
: string lastName
: integer age
: string[] ...favoriteHobbies
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}
换句话说,你不仅可以用参数的名字来调用你的参数(这弥补了核心的可读性),实际上你还可以传递数组(以及对变量的引用--虽然这个功能只在bash 4.3中有效)! 另外,被映射的变量都在本地范围内,就像$1(和其他变量)一样。
使得这个工作的代码非常轻,并且在bash 3和bash 4中都能工作(这些是我测试过的唯一版本)。 如果你对更多类似这样的技巧感兴趣的话,你可以看看我的[Bash Infinity Framework][1],下面的代码是其功能之一。
shopt -s expand_aliases
function assignTrap {
local evalString
local -i paramIndex=${__paramIndex-0}
local initialCommand="${1-}"
if [[ "$initialCommand" != ":" ]]
then
echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
return
fi
while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
do
shift # first colon ":" or next parameter's comma ","
paramIndex+=1
local -a decorators=()
while [[ "${1-}" == "@"* ]]
do
decorators+=( "$1" )
shift
done
local declaration=
local wrapLeft='"'
local wrapRight='"'
local nextType="$1"
local length=1
case ${nextType} in
string | boolean) declaration="local " ;;
integer) declaration="local -i" ;;
reference) declaration="local -n" ;;
arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
"string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
"integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
esac
if [[ "${declaration}" != "" ]]
then
shift
local nextName="$1"
for decorator in "${decorators[@]}"
do
case ${decorator} in
@readonly) declaration+="r" ;;
@required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
@global) declaration+="g" ;;
esac
done
local paramRange="$paramIndex"
if [[ -z "$length" ]]
then
# ...rest
paramRange="{@:$paramIndex}"
# trim leading ...
nextName="${nextName//\./}"
if [[ "${#@}" -gt 1 ]]
then
echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
fi
elif [[ "$length" -gt 1 ]]
then
paramRange="{@:$paramIndex:$length}"
paramIndex+=$((length - 1))
fi
evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "
# continue to the next param:
shift
fi
done
echo "${evalString} local -i __paramIndex=${paramIndex};"
}
alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'
我希望这个例子能帮助你。 它从用户那里获取两个数字,并将它们输入到名为 "add "的函数中(在代码的最后一行),然后 "add "将它们相加并打印出来。
#!/bin/bash
read -p "Enter the first value: " x
read -p "Enter the second value: " y
add(){
arg1=$1 #arg1 gets to be the first assigned argument (note there are no spaces)
arg2=$2 #arg2 gets to be the second assigned argument (note there are no spaces)
echo $(($arg1 + $arg2))
}
add x y #feeding the arguments
我想我''d pipe in with mention of another way to pass named parameters to bash... 通过引用传递. 从bash 4.0开始,这个方法已经被支持了。
#!/bin/bash
function myBackupFunction(){ # directory options destination filename
local directory="$1" options="$2" destination="$3" filename="$4";
echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
}
declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );
myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];
bash 4.3的另一种语法是使用[nameref][1]。
虽然 nameref 更加方便,因为它可以无缝地解除引用,但一些旧的支持的发行版仍然运载了一个 [旧版本][2] ,所以我还不太推荐它。
[1]: http://wiki.bash-hackers.org/commands/builtin/declare#nameref [2]: https://launchpad.net/ubuntu/precise/+source/bash
一个简单的例子,它可以在执行脚本的过程中清除,也可以在调用函数时在脚本内部清除。
#!/bin/bash
echo "parameterized function example"
function print_param_value(){
value1="${1}" # $1 represent first argument
value2="${2}" # $2 represent second argument
echo "param 1 is ${value1}" #as string
echo "param 2 is ${value2}"
sum=$(($value1+$value2)) #process them as number
echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" #space sparted value
#you can also pass paramter durign executing script
print_param_value "$1" "$2" #parameter $1 and $2 during executing
#suppose our script name is param_example
# call like this
# ./param_example 5 5
# now the param will be $1=5 and $2=5