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
Variable expansion is different in zsh from that in bash
提问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 支持数组(ksh、bash、zsh),那么最好使用数组:
args=(-a -l)
ls "${args[@]}"
From the zshFAQ:
2.1: Differences from sh and ksh
The classic difference is word splitting, discussed in question 3.1; this catches out very many beginning zsh users.
3.1: Why does $var where var="foo bar" not do what I expect?is the FAQ that covers this question.
经典的区别是分词,在问题3.1 中讨论;这吸引了很多初学 zsh 用户。
3.1: 为什么 $var where var="foo bar" 不符合我的预期?是涵盖此问题的常见问题解答。
From the zshManual:
从zsh手册:
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.
Causes field splitting to be performed on unquoted parameter expansions.
请特别注意,除非设置了选项 SH_WORD_SPLIT,否则未引用参数的单词不会自动在空格上拆分;有关更多详细信息,请参阅下面对此选项的参考。这是与其他壳的重要区别。
导致对不带引号的参数扩展执行字段拆分。

