I have a problem with echo
in my script:
echo -n "Some string..."
prints
-n Some string...
and moves to the next line. In the console it's working correcly without newline:
Some string...
I have a problem with echo
in my script:
echo -n "Some string..."
prints
-n Some string...
and moves to the next line. In the console it's working correcly without newline:
Some string...
There are multiple versions of the echo
command, with different behaviors. Apparently the shell used for your script uses a version that doesn't recognize -n
.
The printf
command has much more consistent behavior. echo
is fine for simple things like echo hello
, but I suggest using printf
for anything more complicated.
What system are you on, and what shell does your script use?
#!/bin/bash
it worked. Normally I'm working with bash.
– qwertz
Jun 25 '12 at 16:46
printf
command.
– Keith Thompson
Sep 24 '16 at 20:37
echo
always adds newlines... The workaround is jenky at best.
– kayleeFrye_onDeck
Sep 26 '16 at 17:58
bash
has a "built-in" command called "echo":
$ type echo
echo is a shell builtin
Additionally, there is an "echo" command that is a proper executable (that is, the shell forks and execs /bin/echo
, as opposed to interpreting echo
and executing it):
$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21 2011 /bin/echo
The behavior of either echo
's WRT to \c
and -n
varies. Your best bet is to use printf
, which is available on four different *NIX flavors that I looked at:
$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"
Try with
echo -e "Some string...\c"
It works for me as expected (as I understood from your question).
Note that I got this information from the man
page. The man
page also notes the shell may have its own version of echo
, and I am not sure if bash
has its own version.
echo "some string...\c"
instead. If however you need to support multiple bash variants with wildly differing echo commands you probably are better of using printf or you need to be checking the echo commands capabilities with something like [ -n "$( echo -e )" ] && echo "sh stuff\c" || echo -e "bash stuff\c"
(at least bash supports \c as well, so no need to use the -n option, but you need the -e for bash)
– Timo
Oct 19 '16 at 10:26
If you use echo inside an if with other commands, like "read", it might ignore the setting and it will jump to a new line anyway.
bash
in bourne shell mode, it works fine here. Also, it's somewhat unlikely you're really using a bourne shell as your interactive shell, no? – FatalError Jun 25 '12 at 16:41echo -ne "text without new line: "; echo "some text";
– zsoltii Apr 26 '16 at 9:01