How to execute MySQL query and bash command together in one script?

Viewed 65

I want to execute multiple SQL queries in a bash script. The queries are loading files with similar names. For example: File1.csv, File2.csv ... I know that I can use

mysql -u root -p <<EOF MYSQL QUERY 1 MYSQL QUERY 2 ... Can I use bash variables in those queries? I have also tried code like

for f in $dir; do 
echo "SET foreign_key_checks = 0; LOAD DATA LOCAL INFILE '$f' INTO TABLE $table CHARACTER SET UTF8 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n';"
done`

However, the last time I execute a script like this, my table is crashed. The sample script I used to write the above script is

  for f in $dumpDir/*.csv ; do
  table=`basename $f|cut -f1 -d'.'`
  echo "`date` Restoring table $table"
  echo "SET foreign_key_checks = 0; LOAD DATA LOCAL INFILE '$f' INTO TABLE $table CHARACTER SET UTF8 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n';" |$mysql || exit 1
done

Is my table crashed becasue I'm missing the part |$mysql || exit 1?

1 Answers

I fixed this by appending |$mysql ||exit 1 after the MYSQL query. I also used the configuration from the ghtorrent project. original code

Related