简体   繁体   English

在bash中使用读取命令运行功能

[英]Running function with read command in bash

I need small help with shell function.我需要 shell 功能方面的小帮助。 I created small function with read command inside, I need to call this function and the return value to outside variable我在内部创建了带有 read 命令的小函数,我需要调用这个函数并将返回值返回给外部变量

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.我希望这个函数像 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.如果您在提示结束前按CTRL+C并尝试回显$out ,您会注意到您的提示已保存到$out变量中。 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.如果您专门使用 bash,请考虑read -p

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.这样,它将写入 stderr 而不是 stdout,所以它不会被吃掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM