击.继承函数范围

vad*_*shb 3 bash scope

我需要一个全局计数器和函数来逐个返回数字.例如,我希望这个脚本回显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;)&
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得6,7,8?

更新: 好的,在chepner的回答后,我需要指出一点我的问题.如果我需要使用get_free_port变量foo,我不能使用这种方法,不是吗?所以我不能写

function foo {
    variable=get_free_port # variable=$(get_free_port) was ok, but returns 6,6,6
    echo ${variable}
}
Run Code Online (Sandbox Code Playgroud)

而且foo &- 像用法一样是不可取的

che*_*ner 5

您无法修改子流程中的变量($(...)运行的是什么).在这种情况下你不需要一个:

function foo {
    get_free_port
}
Run Code Online (Sandbox Code Playgroud)

但是,出于同样的原因,您也无法foo从子shell或后台作业调用.既不会foo &,(foo)(foo)&不会更新port_counter当前shell中的值.

如果您确实需要调用get_free_port 捕获其输出,则需要使用临时文件.例如:

foo () {
    get_free_port > some_temp_file
    cat some_temp_file
}
Run Code Online (Sandbox Code Playgroud)

如果这不合适,您可能需要重新考虑脚本的设计.