Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print (echo) messages without line breaks in BASH?

I am creating a .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 of this:

Welcome jsmith
!

How can I get all of this onto one line?

Any help is greatly appreciated. If it helps, I'm using the Bash Shell, on Ubuntu Server 10.04 LTS.

like image 368
Oliver Spryn Avatar asked Nov 16 '25 07:11

Oliver Spryn


1 Answers

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

like image 151
John Kugelman Avatar answered Nov 19 '25 08:11

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!