use*_*822 20 bash parameter function syntax
我想编写一个函数,我可以从具有许多不同变量的脚本中调用该函数。由于某些原因,我在这样做时遇到了很多麻烦。我读过的例子总是只使用一个全局变量,但就我所见,这不会使我的代码更具可读性。
预期用途示例:
#!/bin/bash
#myscript.sh
var1=$1
var2=$2
var3=$3
var4=$4
add(){
result=$para1 + $para2
}
add $var1 $var2
add $var3 $var4
# end of the script
./myscript.sh 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
我尝试$1在函数中使用等,但是它只需要调用整个脚本的全局函数。基本上我正在寻找的是类似的东西$1,$2等等,但在函数的本地上下文中。如您所知,函数可以在任何适当的语言中工作。
Rah*_*hul 24
调用带参数的函数:
function_name "$arg1" "$arg2"
Run Code Online (Sandbox Code Playgroud)
该函数通过它们的位置(而不是名称)来引用传递的参数,即 $1、$2 等等。$0 是脚本本身的名称。
例子:
#!/bin/bash
add() {
result=$(($1 + $2))
echo "Result is: $result"
}
add 1 2
Run Code Online (Sandbox Code Playgroud)
输出
./script.sh
Result is: 3
Run Code Online (Sandbox Code Playgroud)
在主脚本中,$1、$2 表示您已经知道的变量。在下标或函数中,$1 和 $2 将表示传递给函数的参数,作为此下标的内部(局部)变量。
#!/bin/bash
#myscript.sh
var1=$1
var2=$2
var3=$3
var4=$4
add(){
#Note the $1 and $2 variables here are not the same of the
#main script...
echo "The first argument to this function is $1"
echo "The second argument to this function is $2"
result=$(($1+$2))
echo $result
}
add $var1 $var2
add $var3 $var4
# end of the script
./myscript.sh 1 2 3 4
Run Code Online (Sandbox Code Playgroud)