#!/bin/bash echo"parameterized function example" functionprint_param_value(){ value1="${1}"# $1 代表第一个参数 value2="${2}"# $2 代表第二个参数 echo"param 1 is ${value1}"# 作为字符串 echo"param 2 is ${value2}" sum=$(($value1+$value2)) # 作为数字处理 echo"The sum of two value is ${sum}" } print_param_value "6""4"# 以空格分隔的值 print_param_value "$1""$2"# 脚本执行时的参数 $1 和 $2
传递数组示例
1 2 3 4 5 6 7 8 9
functioncallingSomeFunction () { for value in"$@"; do# 使用 "$@" 处理所有参数 : done }
functionlinearSearch () { local myVar="$1" shift 1 # 从参数列表中移除 $1 for value in"$@"; do# 表示剩余的参数 if [[ $value == $myVar ]]; then echo -e "Found it!\t... after a while." return 0 fi done return 1 }
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}" # 去除前导的 ... 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