zsh 中的变量扩展与 bash 中的不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6715388/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:23:03  来源:igfitidea点击:

Variable expansion is different in zsh from that in bash

bashshellzsh

提问by Shrikant Sharat

The following is a simple test case for what I want to illustrate.

下面是我想说明的一个简单的测试用例。

In bash,

在 bash 中,

# define the function f
f () { ls $args; }

# Runs the command `ls`
f

# Runs the fommand `ls -a`
args="-a"
f

# Runs the command `ls -a -l`
args="-a -l"
f

But in zsh

但是在zsh 中

# define the function f
f () { ls $args }

# Runs the command `ls`
f

# Runs the fommand `ls -a`
args="-a"
f

# I expect it to run `ls -a -l`, instead it gives me an error
args="-a -l"
f

The last line in the zsh on above, gives me the following error

上面 zsh 中的最后一行,给了我以下错误

ls: invalid option -- ' '
Try `ls --help' for more information.

I think zshis executing

我认为zsh正在执行

ls "-a -l"

which is when I get the same error. So, how do I get bash's behavior here?

这是当我遇到相同的错误时。那么,我如何在这里获得 bash 的行为?

I'm not sure if I'm clear, let me know if there is something you want to know.

我不确定我是否清楚,如果您有什么想知道的,请告诉我。

回答by Chris Johnsen

The difference is that (by default) zshdoes not do word splitting for unquoted parameter expansions.

不同之处在于(默认情况下)zsh不对未引用的参数扩展进行分词。

You can enable “normal” word splitting by setting the SH_WORD_SPLIT option or by using the =flag on an individual expansion:

您可以通过设置 SH_WORD_SPLIT 选项或=在单个扩展上使用标志来启用“正常”分词:

ls ${=args}

or

或者

setopt SH_WORD_SPLIT
ls $args

If your target shells support arrays (ksh, bash, zsh), then you may be better off using an array:

如果您的目标 shell 支持数组(kshbashzsh),那么最好使用数组:

args=(-a -l)
ls "${args[@]}"


From the zshFAQ:

zsh常见问题解答

From the zshManual:

zsh手册

  • 14.3 Parameter Expansion

    Note in particular the fact that words of unquoted parameters are not automatically split on whitespace unless the option SH_WORD_SPLIT is set; see references to this option below for more details. This is an important difference from other shells.

  • SH_WORD_SPLIT

    Causes field splitting to be performed on unquoted parameter expansions.

  • 14.3 参数扩展

    请特别注意,除非设置了选项 SH_WORD_SPLIT,否则未引用参数的单词不会自动在空格上拆分;有关更多详细信息,请参阅下面对此选项的参考。这是与其他壳的重要区别。

  • SH_WORD_SPLIT

    导致对不带引号的参数扩展执行字段拆分。