"echo" 和 "echo -n" 有什么区别?

What is the difference between "echo" and "echo -n"?

终端上 echo -n 的手册页如下:

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

当我尝试通过以下方式生成 MD5 哈希时:

echo "password" | md5

它returns 286755fad04869ca523320acce0dc6a4

当我做的时候

echo -n "password"

它return是在线MD5生成器return的值:5f4dcc3b5aa765d61d8327deb882cf99

选项-n有什么区别?我不明白终端中的条目。

当您执行 echo "password" | md5 时,echo 会向要散列的字符串添加换行符,即 password\n。当您添加 -n 开关时,它不会,因此只有字符 password 被散列。

最好使用 printf,它会按照您的指示执行操作,而无需任何开关:

printf 'password' | md5

对于 'password' 不只是文字字符串的情况,您应该改用格式说明符:

printf '%s' "$pass" | md5

这意味着密码中的转义字符(例如 \n\t)不会被 printf 解释,而是按字面打印。

echo 单独添加一个新行,而 echo -n 没有。

来自 man bash:

echo [-neE] [arg ...]

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

考虑到这一点,使用 printf 总是更安全,它提供与 echo -n 相同的功能。即不添加默认的新行:

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

有关详细信息,请参阅 Why is printf better than echo? 中的出色答案。

另一个例子:

$ 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