Bash脚本分配和比较
我从命令行运行此脚本:Bash脚本分配和比较,bash,Bash,我从命令行运行此脚本: check_databse_exist=`mysql -u root --password=root -Bse 'show databases' | egrep -v 'information_schema|mysql'` for db in $check_databse_exist; do if [ "$db" == "test_traffic" ] ; then exist=1 fi done if [ $exist -eq 1 ] ; then #do
check_databse_exist=`mysql -u root --password=root -Bse 'show databases' | egrep -v 'information_schema|mysql'`
for db in $check_databse_exist; do
if [ "$db" == "test_traffic" ] ; then
exist=1
fi
done
if [ $exist -eq 1 ] ; then
#do other stuff
fi
exit 0
为什么它会给予:
[: 16: jobeet: unexpected operator
[: 16: jobeet_test: unexpected operator
[: 16: landpage_db: unexpected operator
[: 16: my_db: unexpected operator
[: 16: symfony2: unexpected operator
./cibuild: 24: [0: not found
我只想循环,如果找到集合exist=1谢谢将其更改为:
check_databse_exist=`mysql -u root --password=root -Bse 'show databases' | egrep -v 'information_schema|mysql'`
for db in $check_databse_exist; do
if [ "$db" == "test_traffic" ] ; then
exist=1
fi
done
if [ $exist -eq 1 ] ; then
#do other stuff
fi
exit 0
将其更改为:
check_databse_exist=`mysql -u root --password=root -Bse 'show databases' | egrep -v 'information_schema|mysql'`
for db in $check_databse_exist; do
if [ "$db" == "test_traffic" ] ; then
exist=1
fi
done
if [ $exist -eq 1 ] ; then
#do other stuff
fi
exit 0
由于shell脚本的特殊性,在方括号中需要空格。它们不是可选的
if [ $exist == 1 ]; then
值得一提的是,如果您只想检查一个表是否存在,而不需要$check\u database\u exist
,则可以对其进行重构。我们的想法是用grep替换for循环
if mysql -u root --password=root -Bse 'show databases' | grep -qw test_traffic; then
# Database exists.
fi
grep-q
不产生输出,它只返回成功或失败grep-w
是可选的,但是一种良好的做法;它会阻止像test\u traffic2
这样的表匹配
由于shell脚本的特殊性,在方括号中需要空格。它们不是可选的
if [ $exist == 1 ]; then
值得一提的是,如果您只想检查一个表是否存在,而不需要$check\u database\u exist
,则可以对其进行重构。我们的想法是用grep替换for循环
if mysql -u root --password=root -Bse 'show databases' | grep -qw test_traffic; then
# Database exists.
fi
grep-q
不产生输出,它只返回成功或失败grep-w
是可选的,但是一种良好的做法;它会阻止像test\u traffic2
这样的表匹配。尝试删除=和==周围的所有空格。请不要反复编辑您的问题,这样以前有用的答案看起来很愚蠢。在极少数情况下,可以透明地添加更多信息,如果有新问题,则可以开始新问题。你的标题和标签应该准确地反映你的问题,经过投票和接受的答案应该适合你的问题,并且你只能接受一个问题。尝试删除=和==周围的所有空格。请不要反复编辑你的问题,这样前一个有用的答案看起来很愚蠢。在极少数情况下,可以透明地添加更多信息,如果有新问题,则可以开始新问题。你的标题和标签应该准确地反映你的问题,经过投票和接受的答案应该适合你的问题,你只能接受一个问题。谢谢我编辑了我的主要帖子(请参阅主要帖子),但仍然得到了[:16:jobeet:unexpected operator[:16:jobeet\u测试:unexpected operator[:16:landpage\u db:unexpected operator][:16:my_db:unexpected operator[:16:symfony2:unexpected operator errors???您似乎仍然缺少一些空间。test命令假定您的数据库名称为operators…谢谢,但我选择了内联if mysql-u root--password=root-Bse'show databases'| grep-qw test_traffic;:)谢谢我编辑了我的主要帖子(请参见主帖子)但仍然可以使用[:16:jobeet:unexpected操作符[:16:jobeet\u测试:unexpected操作符[:16:landpage\u db:unexpected操作符[:16:my\u db:unexpected操作符[:16:symfony2:意外的运算符错误???您似乎仍然缺少一些空间。test命令假定您的数据库名称是运算符…谢谢,但我选择了内联if mysql-u root--password=root-Bse'show databases'| grep-qw test_traffic;:)