我将bash脚本简化为问题的范围。我想知道为什么我这么做。。。
#!/bin/bash
read -p "Please enter your name: " name
function test()
{
while true
do
echo $name
done
}
echo $(test)
CCD_ 1命令不循环终端中的名称。然而,如果我要删除函数并让while
循环本身像这样…
#!/bin/bash
read -p "Please enter your name: " name
while true
do
echo $name
done
它会起作用的。或者如果我这样做,它也会工作
#!/bin/bash
read -p "Please enter your name: " name
function test()
{
echo $name
}
echo $(test)
导致echo
命令不显示名称的原因。只有当echo
命令在while
循环中同时在函数中时,才会发生这种情况。
是什么导致echo命令不显示名称
父shell正在等待子shell退出,然后将命令子教程扩展到其内容。因为子shell永远不会退出(因为它处于一个无休止的循环中(,所以echo
命令永远不会被执行。
echo $(test)
^^ ^ - shell tries to expand command substitution
so it runs a subshell with redirected output
and waitpid()s on it.
^^^^ - subshell executes `test` and never exits
cause its an endless loop.
Parent shell will endlessly wait on subshell to exit.
请注意,test已经是用于测试表达式的非常标准的shell内置程序。定义这样的函数会导致覆盖内置程序,这可能会导致意外的问题。
为了便于阅读,我可以推荐bash指南函数。