在bash for循环中传递变量中的'*'

时间:2014-03-07 11:34:45

标签: bash for-loop

我想知道如何在bash for循环中传递我的变量*。我想在db上运行多个select查询,我想我会像这样使用bash for循环:

for query in "select * from filtertype limit 10;" "select * from filter limit 10;"; do echo $query; echo $query | mysql -uroot -ppassword database; done

问题是*继续像这样扩展:

[Bash]$ for query in "select * from filtertype limit 10;" "select * from filter limit 10;"; do echo $query; echo $query | mysql -uroot -ppassword database; done
select acceptance_test bin build-dist.xml build-path-definitions.xml build.properties build.xml classes config core-def database dependencies dev.properties dist docs dummyFile_pdffile.pdf eclipse_classes findbugsExcludeFilter.xml generated getRevision.sh local.build.properties log nohup.out plugins-defs plugins-framework pmc-api-client pmd_rules.xml port_helper.sh raw_data-pigunit-input-overridden.txt raw_event_data-pigunit-input-overridden.txt raw-pigunit-input-overridden.txt rpmbuild src testArea unit_test web from filtertype limit 10;
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'build-dist.xml build-path-definitions.xml build.properties build.xml classes con' at line 1
select acceptance_test bin build-dist.xml build-path-definitions.xml build.properties build.xml classes config core-def database dependencies dev.properties dist docs dummyFile_pdffile.pdf eclipse_classes findbugsExcludeFilter.xml generated getRevision.sh local.build.properties log nohup.out plugins-defs plugins-framework pmc-api-client pmd_rules.xml port_helper.sh raw_data-pigunit-input-overridden.txt raw_event_data-pigunit-input-overridden.txt raw-pigunit-input-overridden.txt rpmbuild src testArea unit_test web from filter limit 10;
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'build-dist.xml build-path-definitions.xml build.properties build.xml classes con' at line 1
[Bash]$

当我在循环变量周围尝试单引号时,我得到了相同的错误,当我单引号和双引用我得到的星号时:

select \* from filtertype limit 10;
ERROR at line 1: Unknown command '\*'.
select \* from filter limit 10;
ERROR at line 1: Unknown command '\*'.

所以问题是 - 是否可以将带有'*'的字符串变量传递给bash for循环?

A

2 个答案:

答案 0 :(得分:1)

问题是您的变量引用$query未加引号,因此需要进行shell扩展(在本例中为*扩展为当前目录中的文件和目录的名称,这个过程称为路径名扩展。

因此,只需双引号您的变量引用,以保护它们免受扩展:

echo "$query"

答案 1 :(得分:0)

我找到了答案。希望它对其他人至少有用。解决方案是在调用变量时引用变量:

for query in "select * from filtertype limit 10;" "select * from filter limit 10;"; do echo "$query"; echo "$query" |mysql -uroot -ppassword database; done

有效

A