请注意,我说的是通过引用将参数传递给脚本,而不是函数。我已经检查了here和here,他们讨论了使用函数传递参数。
我想要的是调用一个脚本,向其传递一个参数,并使参数成为 shell 中的变量,并在脚本内分配值(这正是
read RESPONSE
命令所发生的情况,其中 RESPONSE 成为中的变量当前 shell 的值由 read
命令指定)。
我知道使用这样的函数(使用
local -n
):
#!/bin/bash
function boo() {
local -n ref=$1
ref="new"
}
SOME_VAR="old"
echo $SOME_VAR
boo SOME_VAR
echo $SOME_VAR
或者像这样(使用
eval
):
function booeval() {
ref=$1
eval $(echo $ref=\"new\")
}
SOME_VAR="old"
echo $SOME_VAR
booeval SOME_VAR
echo $SOME_VAR
按预期工作。但是
local
(或 declare
/typedef
)在函数之外不起作用,并且 eval
似乎在子 shell 中运行,当脚本结束时,变量不会在 shell 中生存。我想要这样的东西:
$ cat /tmp/test.sh
#!/bin/bash
ref=$1
eval $(echo "export $ref=\"new value\"")
$ /tmp/test.sh VAR
$ echo $VAR
$
有什么想法吗?
您无疑知道,子 shell 中分配的内容保留在子 shell 中。
如评论中所述,一种解决方案是不使用子 shell:如果脚本是
source
,则将保留分配。然而,这需要仔细编写脚本,以免产生不需要的副作用。
如果正常调用脚本(作为子 shell),您可能可以通过复杂的 IPC 来解决传递值的问题,但在我看来,您可以通过简单地让脚本输出值而不是尝试分配来完全绕过复杂性它对任何东西:
var=$(script)
您可以使用第一种方法来包装它,以便可以传入变量名称:
assign_to(){
local -n ref=$1
shift
ref=$("$@")
}
例如:
$ myref=myvar
$ assign_to $myref date +%Y
$ declare -p myvar
declare -- myvar="2023"
$