如何分配水珠前pression一个变量在Bash脚本? [英] How to assign a glob expression to a variable in a Bash script?

查看:132
本文介绍了如何分配水珠前pression一个变量在Bash脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code的以下两行bash脚本被执行,LS抱怨说文件不存在:

When the following two lines of code are executed in a bash script, "ls" complains that the files don't exist:

dirs=/content/{dev01,dev02}
ls -l $dirs

当我运行带-x选项的脚本,这似乎是通过单引号内的变量(这将prevent通配):

When I run the script with the -x option, it appears to be passing the variable within single quotes (which would prevent globbing):

+ dirs=/content/{dev01,dev01}
+ ls -l '/content/{dev01,dev01}'
ls: /content/{dev01,dev01}: No such file or directory

如果我执行从我的交互式shell(没有引号)的ls命令,它会返回这两个目录。

If I execute the "ls" command from my interactive shell (sans quotes), it returns the two directories.

我一直在读通过的Bash参考手册(V 3.2),并看不出有任何理由文件匹配不发生(我不是传递-f给shell),或任何东西,我可以设置以确保通配情况。

I've been reading through the Bash Reference Manual (v 3.2) and can't see any reason for filename globbing to not take place (I'm not passing -f to the shell), or anything that I can set to ensure that globbing happens.

推荐答案

我认为这是扩张的顺序:

I think it is the order of expansions:

扩展的顺序是:梅开二度
  扩展
,波浪线扩展,参数,
  变量和算术扩展和
  命令替换(在完成
  左到右的方式),字
  分裂和路径扩展

The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.

因此​​,如果您的变量被取代,括号扩展不会发生了。这对我的作品:

So if your variable is substituted, brace expansion doesn't take place anymore. This works for me:

eval ls $dirs

要非常小心的eval。它将verbatimly执行的东西。所以,如果迪尔斯包含˚F{M,K} T *; some_command ,some_command将在LS完成后执行。它将执行你给评估在当前shell的字符串。它会通过 /内容/ DEV01 /内容/ dev02 来LS,是否存在与否。把 * 的东西,使后一路径膨胀,它会忽略不存在的路径:

Be very careful with eval. It will execute the stuff verbatimly. So if dirs contains f{m,k}t*; some_command, some_command will be executed after the ls finished. It will execute the string you give to eval in the current shell. It will pass /content/dev01 /content/dev02 to ls, whether they exist or not. Putting * after the stuff makes it a pathname-expansion, and it will omit non-existing paths:

dirs=/content/{dev01,dev02}*

我不是100%肯定这一点,但对我来说很有意义。

I'm not 100% sure about this, but it makes sense to me.

这篇关于如何分配水珠前pression一个变量在Bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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