0

I have the following shell script which writes volumes in a find command to a file, and loads that file into a mysql database:

# find all the paths and print them to a file
sudo find $FULFILLMENT/ > $FILE
sudo find $ARCH1/ >> $FILE
sudo find $ARCH2/ >> $FILE
sudo find $MASTERING/ >> $FILE

# load the file into the mysql database, `files`, table `path`
/usr/local/bin/mysql -u root files -e "TRUNCATE path"
/usr/local/bin/mysql -u root files -e "LOAD DATA INFILE '/tmp/files.txt' INTO TABLE path"

TRUNCATE is to be used to delete all the old entries before adding the new. However, if any of the find commands don't work (for example, if the volume isn't accessible), I want it to skip on the two mysql commands. How would I modify the above script to do this?

3 Answers 3

2

This will execute your two mysql commands only if all the find commands succeed:

# find all the paths and print them to a file
sudo find $FULFILLMENT/ > $FILE &&
sudo find $ARCH1/ >> $FILE &&
sudo find $ARCH2/ >> $FILE &&
sudo find $MASTERING/ >> $FILE &&
{
  # load the file into the mysql database, `files`, table `path`
  /usr/local/bin/mysql -u root files -e "TRUNCATE path"
  /usr/local/bin/mysql -u root files -e "LOAD DATA INFILE '/tmp/files.txt' INTO TABLE path"
}

The && operator causes the command on the RHS to run only if the command on the LHS succeeds. The { ... } groups the two mysql commands into one compound command, so either both run (if the last find succeeds) or neither does (if the last find does not succeed).

You can use this if there is more to your script that should run whether or not the finds succeed and the mysql commands run.

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

Comments

0

Something like:

sudo find $FULFILLMENT > $FILE || exit 1

Comments

0

You can use #!/bin/bash -e or add a line with set -e above the find commands. That way, Bash will automatically abort as soon as a command fails. It's good practice to always do this by default, since you rarely want to continue when the previous command fails:

set -e

# find all the paths and print them to a file
sudo find $FULFILLMENT/ > $FILE
sudo find $ARCH1/ >> $FILE
sudo find $ARCH2/ >> $FILE
sudo find $MASTERING/ >> $FILE

# load the file into the mysql database, `files`, table `path`
/usr/local/bin/mysql -u root files -e "TRUNCATE path"
/usr/local/bin/mysql -u root files -e "LOAD DATA INFILE '/tmp/files.txt' INTO TABLE path"

2 Comments

Could you please show a full line of code example of using this?
Uhm, set -e is a full line of code example, but I added it in context in your script.

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.