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,
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.