zsh 中的变量扩展与 bash 中的不同 [英] Variable expansion is different in zsh from that in bash

查看:27
本文介绍了zsh 中的变量扩展与 bash 中的不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我想说明的简单测试用例.

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

在 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

但是在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

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

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

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

我认为 zsh 正在执行

ls "-a -l"

这是我遇到相同错误的时候.那么,我如何在此处获得 bash 的行为?

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

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

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

推荐答案

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

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

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

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

ls ${=args}

setopt SH_WORD_SPLIT
ls $args

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

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

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

<小时>

来自 zsh 常见问题:

经典的区别是分词,在问题 3.1 中讨论;这吸引了很多刚开始使用 zsh 的用户.

The classic difference is word splitting, discussed in question 3.1; this catches out very many beginning zsh users.

  • 3.1: 为什么 $var where var="foo bar" 不行我期望什么? 是涵盖此问题的常见问题解答.

  • 3.1: Why does $var where var="foo bar" not do what I expect? is the FAQ that covers this question.

    来自zsh手册:

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

    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.

  • 这篇关于zsh 中的变量扩展与 bash 中的不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆