Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想知道为什么会这样:
arr=() fun() { arr[$1]=$2; } fun 1 2 echo ${arr[1]} # echoes '2'
但这不是:
arr=() fun() { arr[$1]=$2; } fun 1 2 & wait echo ${arr[1]} # echoes a blank line
通过fun在第二个示例中在后台运行,您可以在子 shell 中运行它。在子 shell 中对数组所做的更改对父 shell 不可见,您在其中回显arr[1].
fun
arr[1]
这是行不通的,因为异步运行函数会创建一个新的 shell 上下文,它不能修改父上下文的环境。这与管道进入控制结构非常相似,在控制结构内修改的变量不会在管道外的父级中修改。