9

I have a cron script on a shared web host that occasionally gets killed. I'd like to make a loop in bash that tries again if it gets killed, because most of the time it will make it. I'm having trouble with the syntax for storing a boolean value :P

#!/bin/bash
VAR=0;

while [ $VAR ]; do
    if nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql; then
        VAR=1;
    fi
done

So the script recovers from a killed process okay, but once it's run properly, the new VAR value doesn't kill the while loop.

What am I doing wrong?

5 Answers 5

10

Try

while [ "$VAR" -eq 0 ]; do

0 and 1 are both considered True because they are not null strings.

Sign up to request clarification or add additional context in comments.

1 Comment

That's right, but for how I wrote it in my script, it should actually be -ne 1 :)
8

No need to you a helper variable, consider using:

while ! mysqldump .....; do :;done

2 Comments

What does the colon mean after do?
No operation: Just to satisfy bash syntax.
4

You could use /bin/true and /bin/false. Although while ! mysqldump .....; do :;done (Jürgen Hötzel's solution) would be better in this case, there are other cases when using true and false are useful.

#!/bin/bash
VAR=true

while $VAR; do
  if nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql; then
    VAR=false
  fi
done

1 Comment

I was going to say "mmmm. Shouldn't it be VAR=true AND var=false ? Because - unless error - VAR=true means assigning the string 'true' to VAR. and VAR=false means assigning 'false' to VAR."... but No, because while $VAR executes $VAR.
3

In Bash, you can do a numeric conditional using double parentheses rather than a string conditional, but the logic is inverted:

#!/bin/bash
VAR=1;

while (( VAR )); do
    if nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql; then
        VAR=0;
    fi
done

Comments

1

I like until better for this... :

i=0
until [ $_done ]; do
   echo stuff...;
   sleep 1;
   (( i++ ));
   if [ "$i" -gt 9 ]; then
      _done=1
   fi
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.