# 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.doif [[ $value == $myVar ]]thenecho -e "Found it!\t... after a while."return 0fidone
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: @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[*]}"}
#!/bin/bash
read -p "Enter the first value: " xread -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
#!/bin/bashecho "parameterized function example"function print_param_value(){value1="${1}" # $1 represent first argumentvalue2="${2}" # $2 represent second argumentecho "param 1 is ${value1}" # As stringecho "param 2 is ${value2}"sum=$(($value1+$value2)) # Process them as numberecho "The sum of two value is ${sum}"}print_param_value "6" "4" # Space-separated value# You can also pass parameters during executing the scriptprint_param_value "$1" "$2" # Parameter $1 and $2 during execution
# Suppose our script name is "param_example".# Call it like this:## ./param_example 5 5## Now the parameters will be $1=5 and $2=5