'echo' without newline in a shell script

2019-01-03 04:37发布

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

4条回答
Deceive 欺骗
2楼-- · 2019-01-03 04:56

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"
查看更多
趁早两清
3楼-- · 2019-01-03 05:07

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.

查看更多
趁早两清
4楼-- · 2019-01-03 05:09

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?

查看更多
放我归山
5楼-- · 2019-01-03 05:15

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.

查看更多
登录 后发表回答