"echo -n" prints "-n"
Solution 1:
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?
Solution 2:
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 with respect 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"
Solution 3:
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.
Solution 4:
To achieve this there are basically two methods which I frequently use:
1. Using the cursor escape character (\c
) with echo -e
Example :
for i in {0..10..2}; do
echo -e "$i \c"
done
# 0 2 4 6 8 10
-
-e
flag enables the Escape characters in the string. -
\c
brings the Cursor back to the current line.
OR
2. Using the printf
command
Example:
for ((i = 0; i < 5; ++i)); do
printf "$i "
done
# 0 1 2 3 4
Solution 5:
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.