What is the difference between “echo” and “echo -n”?

梦想与她 提交于 2019-12-02 06:10:37

问题


The manual page on Terminal for echo -n is the following:

 -n    Do not print the trailing newline character.  This may also be
       achieved by appending `\c' to the end of the string, as is done by
       iBCS2 compatible systems.  Note that this option as well as the
       effect of `\c' are implementation-defined in IEEE Std 1003.1-2001
       (``POSIX.1'') as amended by Cor. 1-2002.  Applications aiming for
       maximum portability are strongly encouraged to use printf(1) to
       suppress the newline character.

 Some shells may provide a builtin echo command which is similar or iden-
 tical to this utility.  Most notably, the builtin echo in sh(1) does not
 accept the -n option.  Consult the builtin(1) manual page.

When I try to do generate an MD5 hash by:

echo "password" | md5

It returns 286755fad04869ca523320acce0dc6a4

When I do

echo -n "password"

It returns the value that online MD5 generators return: 5f4dcc3b5aa765d61d8327deb882cf99

What difference does the option -n do? I don't understand the entry in Terminal.


回答1:


When you do echo "password" | md5, echo adds a newline to the string to be hashed, i.e. password\n. When you add the -n switch, it doesn't, so only the characters password are hashed.

Better to use printf, which does what you tell it to without needing any switches:

printf 'password' | md5

For cases where 'password' isn't just a literal string, you should use a format specifier instead:

printf '%s' "$pass" | md5

This means that escape characters within the password (e.g. \n, \t) aren't interpreted by printf and are printed literally.




回答2:


echo alone adds a new line, whereas echo -n does not.

From man bash:

echo [-neE] [arg ...]

Output the args, separated by spaces, followed by a newline. (...) If -n is specified, the trailing newline is suppressed.

Having this into account, it is always safer to use printf, which provides the same functionality as echo -n. That is, no default new line is added:

$ echo "password" | md5sum
286755fad04869ca523320acce0dc6a4  -
$ echo -n "password" | md5sum
5f4dcc3b5aa765d61d8327deb882cf99  -
$ printf "%s" "password" | md5sum
5f4dcc3b5aa765d61d8327deb882cf99  -   # same result as echo -n

See the superb answer in Why is printf better than echo? for more info.

And another example:

$ echo "hello" > a
$ cat a
hello
$ echo -n "hello" > a
$ cat a
hello$            # the new line is not present, so the prompt follows last line


来源:https://stackoverflow.com/questions/30761986/what-is-the-difference-between-echo-and-echo-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!