bash echo命令在功能循环中被忽略

时间:2020-11-12 19:00:02

标签: bash

我将bash脚本简化为问题的范围。我想知道当我这样做时会怎样...

#!/bin/bash                                
                                            
read -p "Please enter your name: " name    
                                            
function test()                            
{                                          
    while true                             
    do                                     
        echo $name                         
    done                                   
}                                          
                                            
echo $(test)

echo命令不会在终端中循环显示名称。但是,如果我要删除该函数并像这样...本身具有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循环内。

1 个答案:

答案 0 :(得分:3)

什么使echo命令不显示名称

在将命令替换扩展到其内容之前,父外壳正在等待子外壳退出。因为子外壳永远不会退出(因为它处于无休止的循环中),所以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 guide functions

相关问题