我试图搜索如何在Bash函数中传递参数,但出现的总是如何从命令行传递参数。
我想在脚本中传递参数。我试着:
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
但是语法不正确。如何将参数传递给函数?
我试图搜索如何在Bash函数中传递参数,但出现的总是如何从命令行传递参数。
我想在脚本中传递参数。我试着:
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
但是语法不正确。如何将参数传递给函数?
当前回答
去掉括号和逗号:
myBackupFunction ".." "..." "xx"
函数应该是这样的:
function myBackupFunction() {
# Here $1 is the first parameter, $2 the second, etc.
}
其他回答
去掉括号和逗号:
myBackupFunction ".." "..." "xx"
函数应该是这样的:
function myBackupFunction() {
# Here $1 is the first parameter, $2 the second, etc.
}
声明函数有两种典型的方法。我更喜欢第二种方法。
function function_name {
command...
}
or
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
参考:高级bash脚本编写指南。
对高级编程语言(C/ c++, Java, PHP, Python, Perl等)的了解会向外行建议,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.
如果您更喜欢命名形参,则可以(使用一些技巧)实际将命名形参传递给函数(也可以传递数组和引用)。
我开发的方法允许你像这样定义传递给函数的命名参数:
function example { args : string firstName , string lastName , integer age } {
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}
你也可以注解参数为@required或@readonly, create…其余参数,从顺序参数创建数组(例如使用字符串[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开发变得更好更简单,您可以看看我的bash Infinity Framework,下面的代码是它的功能之一。
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 parameter:
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