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

2 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.
Run Code Online (Sandbox Code Playgroud)

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

echo "password" | md5
Run Code Online (Sandbox Code Playgroud)

它返回286755fad04869ca523320acce0dc6a4

当我做

echo -n "password"
Run Code Online (Sandbox Code Playgroud)

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

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

fed*_*qui 6

echoalone 会添加新行,而echo -n不会。

man bash

echo [-neE] [arg ...]

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

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

$ echo "password" | md5sum
286755fad04869ca523320acce0dc6a4  -
$ echo -n "password" | md5sum
5f4dcc3b5aa765d61d8327deb882cf99  -
$ printf "%s" "password" | md5sum
5f4dcc3b5aa765d61d8327deb882cf99  -   # same result as echo -n
Run Code Online (Sandbox Code Playgroud)

请参阅为什么 printf 比 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
Run Code Online (Sandbox Code Playgroud)


Tom*_*ech 5

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

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

printf 'password' | md5
Run Code Online (Sandbox Code Playgroud)

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

printf '%s' "$pass" | md5
Run Code Online (Sandbox Code Playgroud)

这意味着密码内转义字符(例如\n,\t)不被解释printf和字面上打印.