“echo”和“echo -n”有什么区别?

时间:2015-06-10 16:21:14

标签: bash command-line echo osx-mavericks

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

返回 286755fad04869ca523320acce0dc6a4

当我这样做时

echo -n "password"

返回在线MD5生成器返回的值: 5f4dcc3b5aa765d61d8327deb882cf99

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

2 个答案:

答案 0 :(得分:5)

执行echo "password" | md5时,echo会为要散列的字符串添加换行符,即password\n。当您添加-n开关时,它不会,因此只会对字符password进行哈希处理。

最好使用printf,无需任何开关即可完成您的操作:

printf 'password' | md5

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

printf '%s' "$pass" | md5

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

答案 1 :(得分:2)

echo单独添加新行,而echo -n则不添加。

来自man bash

  

回声 [-neE] [arg ...]

     

输出args,用空格分隔,后跟换行符。 (......)   如果指定了-n,则会抑制尾随换行符。

考虑到这一点后,使用printf总是更安全,echo -n提供与$ echo "password" | md5sum 286755fad04869ca523320acce0dc6a4 - $ echo -n "password" | md5sum 5f4dcc3b5aa765d61d8327deb882cf99 - $ printf "%s" "password" | md5sum 5f4dcc3b5aa765d61d8327deb882cf99 - # same result as echo -n 相同的功能。也就是说,没有添加默认的新行:

$ 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

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

另一个例子:

fprintf()