我需要一个全局计数器和函数,它逐个返回数字。例如,我希望这个脚本回显6,7,8(但它回显6,6,6):
#!/bin/bash
port_counter=5
function get_free_port {
port_counter=$((port_counter + 1))
echo ${port_counter}
}
function foo {
echo $(get_free_port)
}
foo
foo
(foo;)&
如何获得6,7,8?
更新:好的,在chepner的回答之后,我需要详细说明我的问题。如果我需要在foo
中使用get_free_port
作为变量,我不能使用这种方法,不是吗?所以我不能写
function foo {
variable=get_free_port # variable=$(get_free_port) was ok, but returns 6,6,6
echo ${variable}
}
类似foo &
的用法也不太理想。
您不能修改子流程中的变量($(...)
就是这样运行的)。在这种情况下,您不需要
function foo {
get_free_port
}
但是,出于同样的原因,您也不能从子shell或后台作业调用foo
。foo &
、(foo)
和(foo)&
都不会更新当前外壳中port_counter
的值。
如果您确实需要调用get_free_port
并捕获其输出,则需要使用一个临时文件。例如:
foo () {
get_free_port > some_temp_file
cat some_temp_file
}
如果这不合适,您可能需要重新考虑脚本的设计。
下面的代码将为您提供所需的行为:
#!/bin/bash
port_counter=5
function get_free_port {
port_counter=$(( port_counter + 1 ))
echo ${port_counter}
}
function foo {
get_free_port
# $(get_free_port) spawns a subshell and the parent shell variables are not
# available in the subshell.
}
foo #runs fine
foo #runs fine
foo #(foo;)& again spawns a subshell and the parent shell pariables are not available here.