如果条件通过,则从 mongo shell 退出 bash 脚本

问题描述

我正在编写一个 bash 脚本。如果条件通过,我需要从 mongo shell 退出 bash 脚本。我试过 quit(0) 但它只退出 shell 并继续执行 bash 脚本的其余部分。

mongo ${ssl_mode} --quiet <<EOF  //connecting to mongo
    {
      if(array.member!== 1) {
           print("Successful Validation.");
           quit(0);                                
      } else {
         //some code
      }
EOF

//rest of the bash script

解决方法

您可以让脚本在 mongo 返回成功时退出:

mongo ${ssl_mode} --quiet <<EOF && exit
    {
      if(array.member!== 1) {
           print("Successful Validation.");
           quit(0);      // exit mongo shell and exit bash script 
      } else {
         //some code
         quit(1);        // exit mongo shell but continue bash script
      }
EOF
,

检查mongo shell的返回码:

mongo ${ssl_mode} --quiet <<EOF  //connecting to mongo
    {
      if(array.member!== 1) {
           print("Successful Validation.");
           quit(33);                                
      } else {
         //some code
      }
EOF
if [[ $? -eq 33 ]] ; then
   exit 0
fi