应用于命令时如何强制 bash/zsh 将参数计算为多个参数
我正在尝试运行这样的程序:
$CMD $ARGS
其中 $ARGS 是一组带空格的参数。然而,zsh 似乎将 $ARGS 的内容作为单个参数传递给可执行文件。这是一个具体的示例:
$export ARGS="localhost -p22"
$ssh $ARGS
ssh: Could not resolve hostname localhost -p22: Name or service not known
是否有 bash 或 zsh 标志来控制此行为?
请注意,当我将此类命令放入 $!/bin/sh 脚本中时,它会按预期执行。
谢谢,
SetJmp
I am trying to run a program like this:
$CMD $ARGS
where $ARGS is a set of arguments with spaces. However, zsh appears to be handing off the contents of $ARGS as a single argument to the executable. Here is a specific example:
$export ARGS="localhost -p22"
$ssh $ARGS
ssh: Could not resolve hostname localhost -p22: Name or service not known
Is there a bash or zsh flag that controls this behavior?
Note that when I put this type of command in a $!/bin/sh script, it performs as expected.
Thanks,
SetJmp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 zsh 中,这很简单:
使用
cmd ${=ARGS}
将$ARGS
按单词拆分为单独的参数(按空格拆分)。使用
cmd ${(f)ARGS}
将$ARGS
按行拆分为单独的参数(按换行符拆分,但不按空格/制表符拆分)。正如其他人提到的,设置 SH_WORD_SPLIT 会默认进行分词,但在您在 zsh 中执行此操作之前,请参见。 http://zsh.sourceforge.net/FAQ/zshfaq03.html 的解释为为什么默认情况下不启用空格分割。
In zsh it's easy:
Use
cmd ${=ARGS}
to split$ARGS
into separate arguments by word (split on whitespace).Use
cmd ${(f)ARGS}
to split$ARGS
into separate arguments by line (split on newlines but not spaces/tabs).As others have mentioned, setting SH_WORD_SPLIT makes word splitting happen by default, but before you do that in zsh, cf. http://zsh.sourceforge.net/FAQ/zshfaq03.html for an explanation as to why whitespace splitting is not enabled by default.
如果您使用
eval $CMD $ARGS
,它将起作用。It will work if you use
eval $CMD $ARGS
.如果您希望在传递给命令之前将字符串变量(也有数组)拆分为单词,请使用
$=VAR
。还有一个选项(shwordsplit
,如果我没记错的话)可以使任何命令 $VAR
的行为类似于命令 $=VAR
,但我建议不要设置它:我发现输入诸如command "$VAR"
(zsh:command $VAR
) 和command 之类的东西非常不方便“${ARRAY[@]}”
(zsh:命令 $ARRAY
)。If you want to have a string variable (there are also arrays) be split into words before passing to a command, use
$=VAR
. There is also an option (shwordsplit
if I am not mistaking) that will make anycommand $VAR
act likecommand $=VAR
, but I suggest not to set it: I find it very inconvenient to type things likecommand "$VAR"
(zsh:command $VAR
) andcommand "${ARRAY[@]}"
(zsh:command $ARRAY
).