可移植性真的很重要:on shell and tr

道理很简单,但是不小心造成的麻烦会很大! 关键词:shell, tr, regexp, [A-Z] vs. ‘[A-Z]’  

  1. Make sure where we are.
  bash-3.2$ pwd
  /home/zedware/test

 

  1. What we have
  bash-3.2$ ls -al
  total 8
  drwxr-xr-x  2 zhangw8 zedware   80 Apr  8 22:11 .
  drwxr-xr-x 21 zedware zedware 3072 Apr  8 22:11 ..

 

  1. Which shell
  bash-3.2$ ps -p $$
    PID TTY          TIME CMD
  27643 pts/0    00:00:00 bash

 

  1. Convert uppercase to lowercase. It works?!
  bash-3.2$ echo Bill | tr [A-Z] [a-z]
  bill

 

  1. Create a file x
  bash-3.2$ touch x
  bash-3.2$ ls -al
  total 8
  drwxr-xr-x  2 zedware zedware   80 Apr  8 22:12 .
  drwxr-xr-x 21 zedware zedware 3072 Apr  8 22:11 ..
  -rw-r--r--  1 zedware zedware    0 Apr  8 22:12 x

 

  1. Convert again. It works? NO!
  bash-3.2$ echo Bill | tr [A-Z] [a-z]
  Bill

 

  1. Why?

[A-Z] and [a-z] are interpreted by current shell - bash as regular expression. Where [a-z] matches x now.

  sh-3.2$ echo Bill | tr [A-Z] x
  Bill

 

  1. Supress the regexp by ‘’. And it works.
  bash-3.2$ echo Bill | tr '[A-Z]' '[a-z]'
  bill

 

  1. Or use the simpler syntax. It also works.
  bash-3.2$ echo Bill | tr A-Z a-z
  bill
  1. Delete file x and try the tests.
  bash-3.2$ rm -rf x
  bash-3.2$ ls -al
  total 8
  drwxr-xr-x  2 zedware zedware   80 Apr  8 22:13 .
  drwxr-xr-x 21 zedware zedware 3072 Apr  8 22:11 ..

 

  1. ’’ still works.
  bash-3.2$ echo Bill | tr '[A-Z]' '[a-z]'
  bill

 

  1. Also works.
  bash-3.2$ echo Bill | tr A-Z a-z
  bill

 

  1. Now, try it in another shell - csh.
  [zedware@fedora ~/test]$ ps -p $$
    PID TTY          TIME CMD
  26144 pts/0    00:00:00 csh

 

  1. It shows error message. That’s better than slient.
  [zedware@fedora ~/test]$ echo Bill | tr [A-Z] [a-z]
  tr: No match.

 

  1. ’’ still works.
  [zedware@fedora ~/test]$ echo Bill | tr '[A-Z]' '[a-z]'
  bill
  1. Also works.
  [zedware@fedora ~/test]$ echo Bill | tr A-Z a-z
  bill

 

  1. Create file x.
  [zedware@fedora ~/test]$ touch x

 

  1. Error out as expected.
  [zedware@fedora ~/test]$ echo Bill | tr [A-Z] [a-z]
  tr: missing operand after `x'
  Two strings must be given when translating.
  Try `tr --help' for more information.

 

  1. ’’ still works.
  [zedware@fedora ~/test]$ echo Bill | tr '[A-Z]' '[a-z]'
  bill

 

  1. Also works.
  [zedware@fedora ~/test]$ echo Bill | tr A-Z a-z
  bill

  Conclusion:

  1. Be careful of the differences among shells.
  2. Always use the standard, portable syntax of shell commands.
[ Shell ]
Written on April 9, 2011