0

I need small help with shell function. I created small function with read command inside, I need to call this function and the return value to outside variable

Check()
{
echo "type something : "
read anyword
echo $anyword
}


out=`Check`
echo $out

the problem is that echo line is not presenting anything until i press enter. I want that this function will act like python.

Thanks,

  • Please note that `$()` syntax has been preferred over backticks since....a really long time ago. Probably circa 1992. Backticks are bad for your health, bad for the planet, and may cause cancer. Also, a kitten dies every time you use them. – William Pursell Mar 17 '20 at 12:01
  • To @WilliamPursell's point, see https://stackoverflow.com/questions/9405478/command-substitution-backticks-or-dollar-sign-paren-enclosed – General Grievance Mar 17 '20 at 12:23

1 Answers1

0

The problem is the backticks. If you CTRL+C before the prompt ends, and try to echo $out, you notice that your prompt is saved into the $out variable. Move the prompt outside the function call. Maybe this will help:

Check()
{
    read anyword
    echo $anyword
}

echo "type something : "
out=`Check`
echo $out

If you're using bash specifically, consider read -p also.

Alternatively, if you want to keep the prompt inside the function:

Check()
{
    echo "Type something: " >&2
    read anyword
    echo $anyword
}

That way, it will write to stderr instead of stdout, so it won't get eaten up.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • You don't have to move the prompt out of the function; just write it to standard error, like `read -p` does. `echo "type something: " >&2`. – chepner Mar 17 '20 at 12:07