|
0b. Notes about using echo This isn't really a FAQ, but discussions about using echo come up often enough that it seems reasonable to have something about it in the FAQ list. The echo command is not consistent in the handling of its arguments from implementation to implementation. Sometimes a string with backslash quoted characters will be interpreted in one way, and sometimes another. Also, if the string being echoed wasn't built into the script itself, then it could have shell metacharacters in it, which could confuse things. In cases where external input is used to build a string to be echoed the string typically should be quoted. For example s="a string with\na newline and\ta tab" Following are some results with various shells: ------ bash: $ echo "$s" a string with\na newline and\ta tab $ echo -e "$s" a string with a newline and a tab ------- pdksh: $ echo "$s" a string with a newline and a tab $ echo -e "$s" $ echo "$s" a string with a newline and a tab -------- ksh88: $ echo "$s" a string with a newline and a tab $ echo -e "$s" -e a string with a newline and a tab ------- ksh93: $ echo "$s" a string with\na newline and\ta tab $ echo -e "$s" -e a string with\na newline and\ta tab Note that ksh93 makes the handling of arguments system dependent when they contain '\', and/or the first argument begins with '-'. ~jlk/kornshell/doc/man93.html POSIX does not allow the -e option. It also makes the result of using -n or any string with '\' in it implementation-defined. However, on XSI-conforming systems, it disallows options, and defines the use of backslash-quoted characters. In general, the behavior of echo is system and/or shell dependent if its arguments contain a backslash, or its first argument is -n or -e. The biggest problem with echo is when using it to output strings that the script got externally (e.g. user input, or reading from a file). These strings may have '\' characters in them for example. In this case, results may not be what you expect. print is available in some shells, although printf(1) is perhaps more portable. Additionally, a here document will give predictable results in that it will not expand escape sequences. cat <<EOF $s EOF produces a string with\na newline and\ta tab So consider not using echo unless you are sure what will happen, given the shell you're using. ====================================================================== [ 本帖最后由 r2007 于 2005-12-3 16:27 编辑 ] |
|
3楼楼长
|
comp.unix.shell FAQ(转载~j.p.h/)
|