如何让 bash 扩展变量中的通配符?
输入相同的效果
mv ./images/*.{pdf,eps,jpg,svg} ./images/junk/
我正在尝试实现与从 bash 脚本内部在命令行 。我有:
MYDIR="./images"
OTHERDIR="./images/junk"
SUFFIXES='{pdf,eps,jpg,svg}'
mv "$MYDIR/"*.$SUFFIXES "$OTHERDIR/"
运行时,会出现意外错误:
mv: rename ./images/*.{pdf,eps,jpg,svg} to ./images/junk/*.{pdf,eps,jpg,svg}:
No such file or directory
引用所有这些内容以便 mv
实际上会进行所需的扩展的正确方法是什么? (是的,有很多文件与 ./images/
中的模式匹配。)
I am trying achieve the same effect as typing
mv ./images/*.{pdf,eps,jpg,svg} ./images/junk/
at the command line, from inside a bash script. I have:
MYDIR="./images"
OTHERDIR="./images/junk"
SUFFIXES='{pdf,eps,jpg,svg}'
mv "$MYDIR/"*.$SUFFIXES "$OTHERDIR/"
which, when run, gives the not unexpected error:
mv: rename ./images/*.{pdf,eps,jpg,svg} to ./images/junk/*.{pdf,eps,jpg,svg}:
No such file or directory
What is the correct way to quote all this so that mv
will actually do the desired expansion? (Yes, there are plenty of files that match the pattern in ./images/
.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除的答案是正确的。对您的尝试稍作修改:
大括号扩展在变量扩展之前完成,但变量扩展在路径名扩展之前完成。因此,当变量在原始文件中扩展时,大括号仍然是大括号,但是当变量包含路径名元素时,它们在路径名扩展完成时已经被扩展。
A deleted answer was on the right track. A slight modification to your attempt:
Brace expansion is done before variable expansion, but variable expansion is done before pathname expansion. So the braces are still braces when the variable is expanded in your original, but when the variable instead contains pathname elements, they have already been expanded when the pathname expansion gets done.
您需要评估该行才能使其正常工作,如下所示:
现在,这有问题,特别是如果您不信任
$SUFFIXES
,它可能包含注入攻击,但对于这个简单的情况应该没问题。如果您愿意接受其他解决方案,您可能想尝试一下
find
和xargs
。You'll need to eval that line in order for it to work, like so:
Now, this has problems, in particular, if you don't trust
$SUFFIXES
, it might contain an injection attack, but for this simple case it should be alright.If you are open to other solutions, you might want to experiment with
find
andxargs
.您可以编写一个函数:
function Expand { for arg in "$@";做 [[ -f $arg ]] &&回显 $arg;完成 }
然后用您想要扩展的内容调用它:
expand "$MYDIR/"*.$SUFFIXES
如果您愿意,您还可以将其设为脚本 Expand.sh。
You can write a function:
function expand { for arg in "$@"; do [[ -f $arg ]] && echo $arg; done }
then call it with what you want to expand:
expand "$MYDIR/"*.$SUFFIXES
You can also make it a script expand.sh if you like.