变量中的通配符,Shell bash,怎么办?变量=$变量2*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15421685/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:51:59  来源:igfitidea点击:

Wildcard in variable, Shell bash, how to do ? Variable=$variable2*

bashshellvariableswildcard

提问by felipe Salomao

For me it worked:

对我来说它有效:

diretorio=$(echo 'test 123'*)

but not worked when i used variable in quotes

但当我在引号中使用变量时不起作用

Var2="test 123" 
diretorio=$(echo '$Var2'*)

How to solve it?

如何解决?

回答by Gilles Quenot

The mistake in your globis that

你的glob 中的错误是

diretorio=$(echo '$Var2'*)

is a shot in /dev/null, because the shelldon't expand variables in single quotes.

是一个镜头/dev/null,因为外壳不会用单引号扩展变量。

So :

所以 :

diretorio=$(echo "$Var2"*)

Learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotesand http://wiki.bash-hackers.org/syntax/words

了解 ' 和 " 和 ` 之间的区别。请参阅http://mywiki.wooledge.org/Quoteshttp://wiki.bash-hackers.org/syntax/words

回答by Gordon Davisson

May I suggest an alternate approach? Instead of making a space-separated list of filenames (which will cause horrible confusion if any of the filenames contain spaces, e.g. "test 123"), use an array:

我可以建议另一种方法吗?而不是制作一个以空格分隔的文件名列表(如果任何文件名包含空格,这将导致可怕的混乱,例如“test 123”),使用数组:

diretorio=("${Var2}"*)
doSomethingWithAllFiles "${diretorio[@]}"
for umDiretorio in "${diretorio[@]}"; do
    doSomethingWithASingleFile "$umDiretorio"
done

回答by jlliagre

Use double quotes:

使用双引号:

diretorio=$(echo "$Var2"*)

Single ones prevent variable substitution

单个防止变量替换