Shell 编程中的 echo 和 printf

来源:互联网 发布:王保安 私生子知乎 编辑:程序博客网 时间:2024/04/28 06:56
近些天翻阅 O'Reilly 的 Learning the Bash Shell 的时候,偶然发现书中的 echo 命令输出和我的机器上的不一样,于是兴致盎然的仔细读了一下 echo 的 man page 发现了这样一句话:

NOTE: your shell may have its own version of echo, which usually supersedes the version described here.  Please refer to your  shell's  documentation for details about the               options it supports.

原来此 echo 非彼 echo 。我使用的是 bash,那么就应该看看 bash 的 man page 了。选项很多,也很复杂,若一一在此列举,不免无聊,于是贴个图:



这张图是我的一系列命令的截屏,不用多说,问题就在 -e 这个奇怪的选项上。不同版本的 echo 缺省的参数并不相同,所以如果想输出指定的格式实在是难。

对于这个难题有几种解决方案。其一是不使用 shell buildins,在命令前加上 env 这个命令,于是 echo 就不再调用 shell buildin 了。不过这样做会牺牲效率,使用 shell buildin 可以大大提高程序运行速度。我的一个朋友 minux 有另外一种思路。他认为脚本中不应该使用 echo 而应该使用 printf,并引用 Rob Pike 的评论说:

I am surprised to learn (again) that 'sh' today means the PWB shell
and its sequelae. I keep hoping we'd left that behind long ago.

Shocking to think that Unix 7th edition is too modern for today's computers.
I give up.

于是我又分别查看了 printf, bash, sh 的 man page 以验证这种说法。当然 printf 也存在不同版本 shell 的区别,但区别很小。我的机器上使用 dash 和 bash,bash 仅比 dash 多了两个选项,而且是两个无关紧要的选项,几乎所有的 format 都是完全相同的,所以就可以用 printf 输出特定格式的字符串,而且是使用 shell buildin,不牺牲程序效率。

总之,我对此最后选择的方案是,对于无格式控制的字符串,直接使用 echo 命令输出,如有格式控制的需要,一律使用 printf,于是所有的问题都解决了。

阅读(23) | 评论(0) | 转发(0) |
0

上一篇:Shell 编程中处理带有空格的文件名的小 trick

下一篇:搬家啦

相关热门文章
  • linux 常见服务端口
  • 什么是shell
  • linux socket的bug??
  • linux的线程是否受到了保护?...
  • 一个适用于windows和linux的抓...
  • linux源码分析1---启动分析2...
  • zabbix_proxy 配置实例
  • 使用AWK进行数据文件的检测...
  • 批量管理Linux系统服务...
  • linux内核API每天来一发(4)...
给主人留下些什么吧!~~