且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在bash中解析命令行参数-奇怪的行为

更新时间:2022-11-07 17:12:14

因为您使用的 echo 版本采用 -e 作为选项(意思是扩展转义字符").

Because the version of echo you use takes -e as an option (meaning "expand escape characters").

编辑后添加:

对此类型问题的标准答案是"use printf",这是严格准确的,但有些不令人满意. printf 使用起来很烦人,因为它处理多个参数的方式.因此:

The standard response to this type of question is "use printf", which is strictly accurate but somewhat unsatisfactory. printf is a lot more annoying to use because of the way it handles multiple arguments. Thus:

$ echo -e a b c
a b c
$ printf "%s\n" -e a b c
-e
a
b
c
$ printf "%s" -e a b c
-eabc$ # That's not what I wanted either

当然,您只需要记住将整个参数序列都用引号引起来,但这会导致烦人的用引号转义的问题.

Of course, you just need to remember to quote the entire argument sequence, but that can lead to annoying quote-escaping issues.

因此,我为您提供回声:

Consequently, I offer for your echoing pleasure:

$ ech-o() { printf "%s\n" "$*"; }
$ ech-o -e a b c
-e a b c
$