0

I am writing a bash script to monitor my MongoDB status. once it is crash then restart it. the script is as below:

while true
do
    ret = $("mongod --config /etc/mongod.conf")
    if $ret == 0
    then
        echo "I am out with code 0."
        break
    fi
    echo "running again"
done
echo "I am out with code $?"

But it seems doesn't work. Return from the system:

running again
./mongo-text: line 3: mongod --config /etc/mongod.conf: No such file or directory
./mongo-text: line 3: ret: command not found
./mongo-text: line 4: ==: command not found

not sure what the problem is. Any help is appreciated.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ken
  • 1,234
  • 10
  • 16
  • does the user running the script have access to /etc/mongod.conf? – stickabee Jul 08 '19 at 18:25
  • yes, it works fine in linux command line. – Ken Jul 08 '19 at 18:26
  • 2
    I think there are a few problems with that bash script. `ret = $` shouldn't have spaces. `$ret == 0` likely wants `((` around it. shellcheck might be able to help find some of the issues – klhr Jul 08 '19 at 18:36
  • My knowledge on bash is feeble at best but I would think you would need another set of quotes to make `"mongod --config /etc/mongod.conf"` into `"mongod --config '/etc/mongod.conf'"` – ruby_newbie Jul 08 '19 at 19:10

2 Answers2

2

There are several issues in your code:

  • $("mongod --config /etc/mongod.conf") will try to run mongod --config /etc/mongod.conf as a command, with spaces included
  • the if syntax is wrong

You can rewrite it this way:

while :; do
    if mongod --config /etc/mongod.conf; then
        echo "I am out with code 0."
        break
    fi
    echo "running again"
    # probably sleep for a few seconds here
done
echo "I am out with code $?"

For info about if statements, see:

codeforester
  • 39,467
  • 16
  • 112
  • 140
2

Your loop can be made much simpler:

while ! mongod --config /etc/mongod.conf; do
    echo "running again" >&2
    sleep 1
done
if test -n "$VERBOSE"; then echo 'modgod successful'; fi

Note that the if keyword executes a command. So if $ret == 0 attempts to run the command $ret (assuming that variable is non-empty and contains no whitespace) with the arguments == and 0. That is almost certainly not what you intend. It is more typical to write if test "$ret" = 0 or if [ "$ret" = 0 ]. If $ret is empty, then it is attempting to execute the command == with the single argument 0.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • one more question. When I tried to put it to the background with "nohup mongo-text &", it did bring up the mongod program, but itself died. how can I run it in the background? – Ken Jul 08 '19 at 20:04
  • If you want it to run in the background, you'll have a difficult time checking the return status. Unless you `wait` for it, which seems to defeat the purpose of running it in the background. – William Pursell Jul 08 '19 at 21:00