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

fel*_*mao 3 variables bash shell wildcard

对我来说它有效:

diretorio=$(echo 'test 123'*)
Run Code Online (Sandbox Code Playgroud)

但是当我在引号中使用变量时却没有用

Var2="test 123" 
diretorio=$(echo '$Var2'*)
Run Code Online (Sandbox Code Playgroud)

怎么解决?

Gil*_*not 6

你的全局中的错误是

diretorio=$(echo '$Var2'*)
Run Code Online (Sandbox Code Playgroud)

是一个镜头/dev/null,因为shell不会在单引号中扩展变量.

所以:

diretorio=$(echo "$Var2"*)
Run Code Online (Sandbox Code Playgroud)

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


Gor*_*son 4

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

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