Unix Print Output on One Line

2020-02-15 07:57发布

I am creating a Unix .bash_profile script, and I have run into a small problem. Here is a snippet of my code:

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.

5条回答
叛逆
2楼-- · 2020-02-15 08:29

You can do something like:

    echo "Welcome `whoami`!"
查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-15 08:37

You can insert $(command) (new style) or `command` (old style) to insert the output of a command into a double-quoted string.

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.

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].

查看更多
做自己的国王
4楼-- · 2020-02-15 08:37

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.

查看更多
一纸荒年 Trace。
5楼-- · 2020-02-15 08:43

Use this form. Get rid of echo and get away from creating a subshell.

printf 'Welcome %s!\n' "$USER"
查看更多
不美不萌又怎样
6楼-- · 2020-02-15 08:52

Try this:

echo -ne "Welcome `whoami`!\n"

OR

echo -ne "Welcome $(whoami)!\n"
查看更多
登录 后发表回答