ter*_*don 30
优选和最广泛使用的不是一回事。虽然printf由于许多原因更好,但大多数人仍然使用,echo因为语法更简单。
您应该选择的主要原因printf是:
echo 不是标准化的,它在不同的系统上会有不同的表现。很难预测当您使用echo foo. 为了说明,在我的 Debian 系统上:
$ type -a echo
echo is a shell builtin
echo is /bin/echo
Run Code Online (Sandbox Code Playgroud)
如您所见,有两种不同的echo命令,一种是内置的 shell(在本例中为 bash),另一种是单独的二进制文件。请注意,它bash也有一个printf内置函数,但它的行为更加标准化,因此问题不大(感谢@RaduR?deanu 指出)。
由于echo支持命令行开关的一些(但不是全部)实现,很难打印以-. 虽然许多程序支持--表示开关的结束和参数的开始(例如,grep -- -a file将找到file包含 的行-a),echo但不支持。那么,你是如何echo打印的-n呢?
$ echo -n ## no output
$ echo '-n' ## no output
$ echo "-n" ## no output
$ echo \-n ## no output
$ echo -e '\055n' ## using the ASCII code works but only on implementations
-n ## that support -e
Run Code Online (Sandbox Code Playgroud)
printf 可以轻松做到这一点:
$ printf -- '-n\n'
-n
$ printf '%s\n' -n
-n
$ printf '\055n\n'
-n
Run Code Online (Sandbox Code Playgroud)有关为什么printf比 更好的更多信息echo,请参阅http://unix.stackexchange.com上类似问题的答案:
https://unix.stackexchange.com/a/65819/22222