Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57861
  • 博文数量: 10
  • 博客积分: 20
  • 博客等级: 民兵
  • 技术积分: 177
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-07 23:47
个人简介

读书,运动,编程,生活有此三者足矣

文章分类

全部博文(10)

文章存档

2013年(10)

我的朋友

分类: LINUX

2013-04-18 17:32:42

近些天翻阅 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,于是所有的问题都解决了。

阅读(1646) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~