[英]Assign bash function parameter new value
Is it possible to first pass a parameter to the function and than change its value? 是否可以先将参数传递给函数,然后更改其值?
#!/bin/bash
name=old_name
echo $name #echoes "old_name"
alter () {
$1=new_name #throws error that says 'command not found'
}
alter name
echo $name #I would like to see "new_name" here
Yes, using a nameref: 是的,使用nameref:
alter () {
declare -n foo=$1
foo=new_name
}
See Bash FAQ 006 for more advice and warnings, as well as workarounds for versions of bash
that predate nameref support (ie, 4.2 or earlier). 请参阅Bash FAQ 006,以获取更多建议和警告,以及在nameref支持之前(例如4.2或更早版本)的
bash
版本的变通办法。
You can't do it that way, unfortunately. 不幸的是,您不能那样做。 Also, bash functions can't return values.
另外,bash函数不能返回值。 The usual options are (1) set a global var in the function (yuck), or (2) echo the "return" value and use command substitution to call it.
通常的选项是(1)在函数(yuck)中设置全局变量,或(2)回显“返回”值并使用命令替换来调用它。 Something like this:
像这样:
alter () {
echo "$1 but different"
}
name="Fred"
name=$(alter $name)
echo Name is now $name
returns: Name is now Fred but different
返回:
Name is now Fred but different
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.