如何使用||检查mysql查询是否成功在shell脚本中?

时间:2017-11-04 11:41:34

标签: mysql linux shell

我不确定在哪里放置我的成功消息功能,其功能如下:

    responseMessage() {
    echo "$1" || echo "$2"
}

我这样称呼它:

#!/bin/bash

password='123456'

responseMessage() {
    echo "$1"|| echo "$2"
}

mysql <<MYSQL 
UPDATE users SET password='${password}' where ID='1';

MYSQL && responseMessage "Successfully updated password." "Failed to update password"

我不确定我应该把这个功能放在哪里。

将它放在上面示例中的位置,我得到以下内容:

user@DESKTOP:~$ bash testmysql.sh
testmysql.sh: line 12: warning: here-document at line 9 delimited by end-of-file (wanted `MYSQL')
ERROR 1046 (3D000) at line 1: No database selected

我希望No Database选择错误,因为它是正确的,但是我希望打印出responseMessage的第二个参数。

这是明显的吗? 感谢

编辑: 还尝试了以下内容:

user@DESKTOP:~$ bash testmysql.sh
ERROR 1046 (3D000) at line 2: No database selected
user@DESKTOP:~$ cat testmysql.sh
#!/bin/bash

responseMessage() {
    echo "$1" || echo "$2"
}

mysql <<MYSQL && responseMessage "Successfully updated password." "Failed to update password"

UPDATE users SET password='123456' where ID='1';

MYSQL

根据https://github.com/koalaman/shellcheck/wiki/SC1121

,我会认为这会奏效

-

我还创建了基于此的函数,它完成了我所期望的:

user@DESKTOP:~$ bash testmysql.sh
ERROR 1046 (3D000) at line 2: No database selected
Failed to recreate the schemata.
user@DESKTOP:~$ cat testmysql.sh
#!/bin/bash

responseMessage() {
    echo "$1" || echo "$2"
}

mysql <<MYSQL && echo "Successfully recreated the schemata." || echo "Failed to recreate the schemata."

UPDATE users SET password='123456' where ID='1';

MYSQL

2 个答案:

答案 0 :(得分:0)

mysql <<MYSQL && responseMessage "Successfully updated password." "Failed to update password"

您的函数responseMessage将打印“已成功重新创建架构”。当mysql成功时,如果你想要的话,但如果因为你把它放在&&之后就失败了。换句话说,您的代码读取“_If且仅当mysql成功,运行我的函数,否则什么也不做”,并且您的函数读取“打印出第一个参数,或者如果打印第一个参数失败,则打印第二个参数。“

你想要的功能看起来更像是这样:

responseMessage() {
  returnCode="$1"
  successMessage="$2"
  failureMessage="$3"
  if [[ $returnCode == "0" ]]; then
    echo "$successMessage"
  else
    echo "$failureMessage"
  fi
}

你的命令将成为:

mysql <<MYSQL; responseMessage $? "Successfully updated password." "Failed to update password"

如果您愿意,可以使用换行符而不是分号。当然,只有在您要检查的命令之后立即调用该函数时,这才有效,否则$?将具有另一个命令的退出代码。

答案 1 :(得分:0)

我已经离开使用heredoc并检查退出代码值。这仍然没有真正解决我想把我的回答变成一个函数,但它比我以前做的更好。

result=$(mysql <<MYSQL

UPDATE users SET password='123456' where ID='1';

MYSQL

)

[ $? = 0 ] && echo "Success" || echo "Failed"
相关问题