可移植性真的很重要:on shell and tr
道理很简单,但是不小心造成的麻烦会很大! 关键词:shell, tr, regexp, [A-Z] vs. ‘[A-Z]’
- Make sure where we are.
bash-3.2$ pwd
/home/zedware/test
- 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 ..
- Which shell
bash-3.2$ ps -p $$
PID TTY TIME CMD
27643 pts/0 00:00:00 bash
- Convert uppercase to lowercase. It works?!
bash-3.2$ echo Bill | tr [A-Z] [a-z]
bill
- 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
- Convert again. It works? NO!
bash-3.2$ echo Bill | tr [A-Z] [a-z]
Bill
- 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
- Supress the regexp by ‘’. And it works.
bash-3.2$ echo Bill | tr '[A-Z]' '[a-z]'
bill
- Or use the simpler syntax. It also works.
bash-3.2$ echo Bill | tr A-Z a-z
bill
- 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 ..
- ’’ still works.
bash-3.2$ echo Bill | tr '[A-Z]' '[a-z]'
bill
- Also works.
bash-3.2$ echo Bill | tr A-Z a-z
bill
- Now, try it in another shell - csh.
[zedware@fedora ~/test]$ ps -p $$
PID TTY TIME CMD
26144 pts/0 00:00:00 csh
- It shows error message. That’s better than slient.
[zedware@fedora ~/test]$ echo Bill | tr [A-Z] [a-z]
tr: No match.
- ’’ still works.
[zedware@fedora ~/test]$ echo Bill | tr '[A-Z]' '[a-z]'
bill
- Also works.
[zedware@fedora ~/test]$ echo Bill | tr A-Z a-z
bill
- Create file x.
[zedware@fedora ~/test]$ touch x
- 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.
- ’’ still works.
[zedware@fedora ~/test]$ echo Bill | tr '[A-Z]' '[a-z]'
bill
- Also works.
[zedware@fedora ~/test]$ echo Bill | tr A-Z a-z
bill
Conclusion:
- Be careful of the differences among shells.
- Always use the standard, portable syntax of shell commands.
[
Shell
]
Written on April 9, 2011