Linux Shell 脚本,在回显消息后在同一行读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9720168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell Script, read on same line after echoing a message
提问by user1263746
Following the shell script that I am executing
按照我正在执行的 shell 脚本
#!/bin/sh
echo "Enter [y/n] : "
read opt
Its output is
它的输出是
Enter [y/n] :
Y
I want that the variable should be read on the same line like below
我希望变量应该像下面一样在同一行上读取
Enter [y/n] : Y
Should be simple I guess, but I am new to bash scripting.
我想应该很简单,但我是 bash 脚本的新手。
采纳答案by TaylanUB
The shebang #!/bin/sh
means you're writing code for either the historical Bourne shell (still found on some systems like Solaris I think), or more likely, the standard shell language as defined by POSIX. This means that read -p
and echo -n
are both unreliable.
shebang#!/bin/sh
意味着您正在为历史悠久的 Bourne shell(我认为仍然可以在某些系统上找到,例如 Solaris)或更可能为 POSIX 定义的标准 shell 语言编写代码。这意味着read -p
和echo -n
都不可靠。
The standard/portable solution is:
标准/便携式解决方案是:
printf 'Enter [y/n] : '
read -r opt
(The -r
prevents the special treatment of \
, since read
normally accepts that as a line-continuation when it's at the end of a line.)
(-r
防止 的特殊处理\
,因为read
当它位于行尾时,通常将其作为行延续接受。)
If you know that your script will be run on systems that have Bash, you can change the shebang to #!/bin/bash
(or #!/usr/bin/env bash
) and use all the fancy Bash features. (Many systems have /bin/sh
symlinked to bash
so it works either way, but relying on that is bad practice, and bash
actually disables some of its own features when executed under the name sh
.)
如果您知道您的脚本将在具有 Bash 的系统上运行,您可以将 shebang 更改为#!/bin/bash
(或#!/usr/bin/env bash
) 并使用所有花哨的 Bash 功能。(许多系统都有/bin/sh
符号链接,bash
所以它可以以任何一种方式工作,但依赖于这种做法是不好的做法,并且bash
在名称下执行时实际上禁用了一些自己的功能sh
。)
回答by Ignacio Vazquez-Abrams
Solution: read -p "Enter [y/n] : " opt
解决方案: read -p "Enter [y/n] : " opt
From help read
:
来自help read
:
-p prompt output the string PROMPT without a trailing newline before
attempting to read
回答by heldt
echo -n "Enter [y/n] : " ; read opt
OR! (Later is better)
或者!(后期更好)
read -p "[y/n]: " opt