如何在Bash变量中存储大括号 [英] How to store curly brackets in a Bash variable

查看:84
本文介绍了如何在Bash变量中存储大括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写bash脚本.我不确定为什么在我的脚本中:

I am trying to write a bash script. I am not sure why in my script:

ls {*.xml,*.txt} 

可以,但是

name="{*.xml,*.txt}"
ls $name

不起作用.我知道了

ls: cannot access {*.xml,*.txt}: No such file or directory

推荐答案

表达式

ls {*.xml,*.txt}

结果为括号扩展和shell传递将扩展名(如果有)扩展为ls作为参数.设置shopt -s nullglob会使在没有匹配文件的情况下该表达式的计算结果为空.

results in Brace expansion and shell passes the expansion (if any) to ls as arguments. Setting shopt -s nullglob makes this expression evaluate to nothing when there are no matching files.

用双引号引起来的字符串抑制了扩展,shell将文字内容存储在变量name中(不确定这是否是您想要的).当您使用$name作为参数调用ls时,shell会进行变量扩展,但不会进行大括号扩展.

Double quoting the string suppresses the expansion and shell stores the literal contents in your variable name (not sure if that is what you wanted). When you invoke ls with $name as the argument, shell does the variable expansion but no brace expansion is done.

正如@Cyrus所提到的,eval ls $name将强制括号扩展,并且您将获得与ls {\*.xml,\*.txt}相同的结果.

As @Cyrus has mentioned, eval ls $name will force brace expansion and you get the same result as that of ls {\*.xml,\*.txt}.

这篇关于如何在Bash变量中存储大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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