bash Unix 一行打印输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6989275/
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
Unix Print Output on One Line
提问by Oliver Spryn
I am creating a Unix .bash_profile script, and I have run into a small problem. Here is a snippet of my code:
我正在创建一个 Unix .bash_profile 脚本,但遇到了一个小问题。这是我的代码片段:
echo -n "Welcome "
whoami
echo -n "!"
I would like the output to give something like this:
我希望输出给出如下内容:
Welcome jsmith!
... instead, I am getting something like this:
......相反,我得到了这样的东西:
Welcome jsmith
!
How can I get all of this onto one line? Any help is greatly appreciated. If this helps, I am using the Bash Shell, on Ubuntu Server 10.04 LTS.
我怎样才能把所有这些都放在一条线上?任何帮助是极大的赞赏。如果这有帮助,我将在 Ubuntu Server 10.04 LTS 上使用 Bash Shell。
回答by John Kugelman
You can insert $(command)(new style) or `command`(old style) to insert the output of a command into a double-quoted string.
您可以插入$(command)(新样式)或`command`(旧样式)以将命令的输出插入双引号字符串中。
echo "Welcome $(whoami)!"
Note: In a script this will work fine. If you try it at an interactive command line the final !may cause you trouble as !triggers history expansion.
注意:在脚本中,这将正常工作。如果您在交互式命令行中尝试它,final!可能会给您带来麻烦,因为它!会触发历史扩展。
Command Substitution
Command substitution allows the output of a command to replace the command name. There are two forms:
$(command)or
`command`Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted[emphasis added].
命令替换
命令替换允许命令的输出替换命令名称。有两种形式:
$(command)或者
`command`Bash 通过执行命令并用命令的标准输出替换命令替换来执行扩展,并删除任何尾随的换行符[强调添加]。
回答by c00kiemon5ter
Use this form. Get rid of echoand get away from creating a subshell.
使用此表格。摆脱echo并摆脱创建subshell。
printf 'Welcome %s!\n' "$USER"
回答by crk
Try this:
尝试这个:
echo -ne "Welcome `whoami`!\n"
OR
或者
echo -ne "Welcome $(whoami)!\n"
回答by Tom Anderson
You probably want:
你可能想要:
echo "Welcome $(whoami)!"
The $()construct executes the command inside it, and evaluates to the output of it.
该$()构造执行其中的命令,并评估其输出。
Another option would be:
另一种选择是:
{
echo "Welcome "
whoami
echo "!"
} | tr -d '\n'
Although that's a bit mad.
虽然这有点疯狂。
Whatever you do, you might need single quotes around the !. In my shell, !is a history metacharacter even inside double quotes.
无论您做什么,您可能都需要将!. 在我的 shell 中,!即使在双引号内也是一个历史元字符。
回答by pmohandas
You can do something like:
您可以执行以下操作:
echo "Welcome `whoami`!"

