Reputation: 1156
I simplified my bash script to the scope of the problem. I was wondering how come when I do this...
#!/bin/bash
read -p "Please enter your name: " name
function test()
{
while true
do
echo $name
done
}
echo $(test)
the echo
command doesn't loop the name in the terminal. However, if I were to remove the function and have the while
loop by itself like so....
#!/bin/bash
read -p "Please enter your name: " name
while true
do
echo $name
done
It would work. Or if I do this, it will also work
#!/bin/bash
read -p "Please enter your name: " name
function test()
{
echo $name
}
echo $(test)
What's causing the echo
command to not to not display the name. This only happens when the echo
command is inside a while
loop whilst being inside a function.
Upvotes: 0
Views: 1300
Reputation: 140940
What's causing the echo command to not to not display the name
The parent shell is waiting for the subshell to exit before expanding the command subsitution to it's contents. Because the subshell never exits (as it's in an endless loop), the echo
command never gets executed.
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.
Note that test is already a very standard shell builtin for testing expressions. Defining such function which will cause to overwrite the builtin may cause unexpected problems.
For some reading I could recommend bash guide functions.
Upvotes: 4