在bash中解析命令行参数-奇怪的行为 [英] Parsing command line arguments in bash - strange behavior
问题描述
#!/bin/bash
for arg
do
echo "$arg"
done
在名为compile的文件中.
In file called compile.
我尝试过:
compile ha -aa -bb -cc -dd -ee -ff -gg
ha
-aa
-bb
-cc
-dd
-ff
-gg
-ee为什么不显示?实际上,似乎[[e] +没有出现.
Why does -ee not show up? In fact, it seems that -[e]+ does not show up.
推荐答案
因为您使用的 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
$
这篇关于在bash中解析命令行参数-奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!