将参数传递给Bash函数

Passing parameters to a Bash function

我试图搜索如何在bash函数中传递参数,但得到的总是如何从命令行传递参数。

我想在脚本中传递参数。我试过:

1
2
3
4
5
myBackupFunction("..","...","xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}

但是语法不正确,如何将参数传递给我的函数?


有两种典型的declaring的功能。我prefer第二种。 P / < >

1
2
3
function function_name {
   command...
}

或 P / < >

1
2
3
function_name () {
   command...
}

到打电话的功能与arguments: P / < >

1
function_name"$arg1""$arg2"

*功能指的是时代不同了arguments通过他们的位置(不by name),那是1美元,2美元,所以四。美元的零的名称为"itself脚本。 P / < >

例子: P / < >

1
2
3
function_name () {
   echo"Parameter #1 is $1"
}

也,你需要对你的呼叫功能后,它也declared。 P / < >

1
2
3
4
5
6
7
8
9
#!/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.

输出: P / < >

1
2
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2

参考:先进的狂欢- scripting指南。 P / < >


知识的高层次的programming languages(C / C + + / / / / Perl Python Java php…)会suggest 的外行,bash功能应该做他们的工作,像那些在其他languages。代替,bash功能工作,像壳牌的命令,以arguments到时代不同了到他们在同样的方式可能会通过一个选项去壳的指挥(LS - L)。在发挥作用,功能arguments在bash是treated年代positional参数($1, $2..$9, ${10}, ${11},所以C)。这不令人惊讶的是考虑如何getopts工程。parentheses是不需要打电话到的功能在狂欢。 P / < >

(注:我想知道,发生在开放Solaris在矩。) P / < >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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"
Tarball created!
"

}


# 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"
Tarball created!
"

}


#In the actual shell script
#$0               $1            $2

backupWebRoot ~/public/www/ webSite.tar.zip


如果你prefer取名为参数,它是可能的(与几tricks)到实际上,通过参数到功能(也使它尽可能到过arrays和references)。 P / < >

同步的方法)发明了allows你定义的参数的功能到时代不同了,像这样: P / < >

1
2
3
function example { args : string firstName , string lastName , integer age } {
  echo"My name is ${firstName} ${lastName} and I am ${age} years old."
}

你也可以annotate arguments岁以下或@ @ readonly,创造...rest arguments,创造arrays从sequential arguments(例如用string[4])和optionally列表的arguments在多线: P / < >

1
2
3
4
5
6
7
8
9
10
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[*]}"
}

在其他的话,不是只有你能呼唤你的参数通过他们的名字(捆起来,为使更多的readable核心),但是你可以通过arrays(和references到变量的描述这个特征的作品只在bash 4.3虽然)。另外,所有的变量的描述是在当地的scope,正如1美元(和其他人)。 P / < >

的代码,使得这项工作很光和工程都在bash Bash 3和4(这些是唯一的版本,我已经与它的身体)。如果你在interested在更多的tricks这样,使开发与多nicer bash和easier,你可以在看我的狂欢无限框架,下面的代码是可用的作为一个functionalities ITS。 P / < >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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;'


小姐出来的parens和commas: P / < >

1
 myBackupFunction"..""...""xx"

和功能应该看起来像这样: P / < >

1
2
3
function myBackupFunction() {
   # here $1 is the first parameter, $2 the second etc.
}

我希望这个例子能帮助你。它需要两个数从用户,他们feeds 功能称为add(在最后一行的代码),和add总和起来,将他们打印他们。 P / < >

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/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


这个简单的例子,将清澈的河流都在executing脚本或内部脚本,而打电话的功能。 P / < >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/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


想过我会在管与提的另一种方式,通过对参数到狂欢……走过的参考。这supported of巴什4号 P / < >

1
2
3
4
5
6
7
8
9
#!/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];

一个替代语法为4.3 bash也用的nameref P / < >

虽然"nameref也很多,它更多的convenient在seamlessly dereferences,一些老年人,老年版仍然supported distros船舶所以我不会被推荐,它的很呢。 P / < >