如何拦截和删除 bash 中的命令行参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21542054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to intercept and remove a command line argument in bash
提问by inspector-g
After "upgrading" to Mavericks and Xcode 5, I have a variety of minor problems to deal with to make Xcode compile some of my older projects.
在“升级”到 Mavericks 和 Xcode 5 之后,我有各种小问题需要处理,以使 Xcode 编译我的一些旧项目。
It appears that Xcode is passing a new argument to the ld
linker, and there's really no stopping Xcode from doing so. An older version of ld
, which I need for a variety of reasons, gives an error when seeing an argument it doesn't know (so my projects cannot compile).
看起来 Xcode 正在向ld
链接器传递一个新参数,而且实际上并没有阻止 Xcode 这样做。ld
由于各种原因我需要一个旧版本的,当看到一个它不知道的参数时会出错(所以我的项目无法编译)。
What I need is a thin wrapper over my older version of ld
to remove the "bad" arguments under certain circumstances. I thought that a bash shell script would be perfect, but bash is not my forte.
我需要的是在我的旧版本上的一个薄包装器,ld
以在某些情况下删除“坏”参数。我认为 bash shell 脚本会很完美,但 bash 不是我的强项。
Here's what I've got:
这是我所拥有的:
# Look for conditions necessary to use older ld
... # (placeholder, obviously)
# Run older ld (pseudo condition)
if [ <old_ld_condition> ]; then
ARGS=''
for var in "$@"; do
# Ignore known bad arguments
if [ "$var" = '-dependency_info' ]; then
continue
fi
ARGS="$ARGS $var"
done
/path/to/old/ld "$ARGS"
else
/path/to/new/ld "$@"
fi
However, running /path/to/old/ld "$ARGS"
results in ld
interpreting the entire $ARGS
string as one argument. Running /path/to/old/ld $ARGS
results in ld
receiving unescaped versions of previously escaped strings.
但是,运行会/path/to/old/ld "$ARGS"
导致ld
将整个$ARGS
字符串解释为一个参数。运行/path/to/old/ld $ARGS
结果会ld
收到以前转义字符串的未转义版本。
Clearly, I'm misunderstanding something about the nature of $@
, how to manipulate it, and how to pass that manipulation to the older ld
. Thanks everyone.
很显然,我误解一些有关的性质$@
,如何处理它,以及如何操纵这传递给上了年纪ld
。谢谢大家。
回答by anubhava
This should work:
这应该有效:
# Run older ld (pseudo condition)
if [ <old_ld_condition> ]; then
ARGS=()
for var in "$@"; do
# Ignore known bad arguments
[ "$var" != '-dependency_info' ] && ARGS+=("$var")
done
/path/to/old/ld "${ARGS[@]}"
else
/path/to/new/ld "$@"
fi
回答by user3159253
You should use Bash Arrays if you really wantto stay with bash:
如果你真的想继续使用 bash,你应该使用 Bash Arrays :
declare -a ARGS
for var in "$@"; do
# Ignore known bad arguments
if [ "$var" = '-dependency_info' ]; then
continue
fi
ARGS[${#ARGS[@]}]="$var"
done
now "${ARGS[@]}"
can be used just as "$@"
. man bash
for more information.
现在"${ARGS[@]}"
可以像"$@"
. man bash
想要查询更多的信息。