我有以下bash脚本,我希望在其中使用跨不同函数重用变量b
,但仍能够使用位置参数进行变量替换
#!/bin/bash
function boo() {
echo "$1"
b="this is b and $1"
echo "$b"
}
function foobar() {
echo "$1"
echo "$b"
}
boo "this is argument 1 for boo"
foobar "this is argument 1 for foobar"
当前输出
$ ./script.sh
this is argument 1 for boo
this is b and this is argument 1 for boo
this is argument 1 for foobar
this is b and this is argument 1 for boo
如何修改脚本以使其输出
$ ./script.sh
this is argument 1 for boo
this is b and this is argument 1 for boo
this is argument 1 for foobar
this is b and this is argument 1 for foobar
答案 0 :(得分:0)
为melponene推荐功能。这似乎是我所需要的。函数不是更依赖于公共变量进行变量扩展,而是更合适
#!/bin/bash
function b_func(){
echo "this is b and $*"
}
function boo() {
echo "$1"
b_var="$(b_func $1)"
echo "$b_var"
}
function foobar() {
echo "$1"
b_var="$(b_func $1)"
echo "$b_var"
}
boo "this is argument 1 for boo"
foobar "this is argument 1 for foobar"
输出:
$ ./script.sh
this is argument 1 for boo
this is b and this is argument 1 for boo
this is argument 1 for foobar
this is b and this is argument 1 for foobar