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?

4

3 回答 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.

于 2013-01-27T22:01:39.040 回答
0

Something like:

sudo find $FULFILLMENT > $FILE || exit 1
于 2013-01-27T20:39:24.103 回答
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"
于 2013-01-27T20:53:18.773 回答