天天看点

可移植性真的很重要: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

2. 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 ..

3. Which shell

bash-3.2$ ps -p $$

  PID TTY          TIME CMD

27643 pts/0    00:00:00 bash

4. Convert uppercase to lowercase. It works?!

bash-3.2$ echo Bill | tr [A-Z] [a-z]

bill

5. 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

6. Convert again. It works? NO!

bash-3.2$ echo Bill | tr [A-Z] [a-z]

Bill

7. 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

8. Supress the regexp by ''. And it works.

bash-3.2$ echo Bill | tr '[A-Z]' '[a-z]'

bill

9. Or use the simpler syntax. It also works.

bash-3.2$ echo Bill | tr A-Z a-z

bill

10. 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 ..

11. '' still works.

bash-3.2$ echo Bill | tr '[A-Z]' '[a-z]'

bill

12. Also works.

bash-3.2$ echo Bill | tr A-Z a-z

bill

13. Now, try it in another shell - csh.

[[email protected] ~/test]$ ps -p $$

  PID TTY          TIME CMD

26144 pts/0    00:00:00 csh

14. It shows error message. That's better than slient.

[[email protected] ~/test]$ echo Bill | tr [A-Z] [a-z]

tr: No match.

15. '' still works.

[[email protected] ~/test]$ echo Bill | tr '[A-Z]' '[a-z]'

bill

16. Also works.

[[email protected] ~/test]$ echo Bill | tr A-Z a-z

bill

17. Create file x.

[[email protected] ~/test]$ touch x

18. Error out as expected.

[[email protected] ~/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.

19. '' still works.

[[email protected] ~/test]$ echo Bill | tr '[A-Z]' '[a-z]'

bill

20. Also works.

[[email protected] ~/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.