#!/bin/bash
for i in /Users/uttambaral/code/zipcodes/*MYSQL-STANDARD.sql
do
echo "Importing: $i"
mysql --host=database-1.12345678 --user=admin --password=123456789 Validation < $i
echo "waiting for import to finish"
done
for i in /Users/uttambaral/code/zipcodes/*database-STANDARD.sql
do
echo "Importing: $i"
mysql --host=database-1.ck1n4yzwola8 --user=admin --password=123456789 Validation < $i
echo "waiting for import to finish"
done
this is my current code, and I am prettry new with scripting so I am not too sure on how to make this code smaller.
trying to consice this code using diffrent kind of loop, maybe while loop or until loop?
CodePudding user response:
There's two opportunities to DRY this code up.
for i in /Users/uttambaral/code/zipcodes/*MYSQL-STANDARD.sql ... for i in /Users/uttambaral/code/zipcodes/*database-STANDARD.sql
Start with
set -e
cd /Users/uttambaral/code/zipcodes
Then you can introduce the wildcard filename globs more concisely.
Or define a DIR
variable, and use that in each glob.
The -e
option ensures we will immediately bail
with fatal error if the directory can't be accessed.
Break out the repeated code as a helper function.
import () {
HOST=$1
FILE=$2
echo "Importing: $FILE"
mysql --host=$HOST --user=admin --password=123456789 Validation < $FILE
echo "waiting for import to finish"
}
Now your for
loops can invoke
import database-1.12345678 $i
or
import database-1.ck1n4yzwola8 $i
CodePudding user response:
How about a case
statement?
#!/bin/sh
for i in /Users/uttambaral/code/zipcodes/*-STANDARD.sql; do
case "$i" in
*MYSQL-STANDARD.sql)
echo "Importing: $i"
mysql --host=database-1.12345678 --user=admin --password=123456789 Validation < "$i"
echo "waiting for import to finish";;
*database-STANDARD.sql)
echo "Importing: $i"
mysql --host=database-1.ck1n4yzwola8 --user=admin --password=123456789 Validation < "$i"
echo "waiting for import to finish";;
esac
done
Using bash
With extglob
and nullglob
#!/usr/bin/env bash
shopt -s extglob nullglob
for i in /Users/uttambaral/code/zipcodes/*@(MYSQL|database)-STANDARD.sql; do
printf 'Importing: %s\n' "$i"
case "$i" in
*MYSQL-STANDARD.sql)
mysql --host=database-1.12345678 --user=admin --password=123456789 Validation < "$i";;
*database-STANDARD.sql)
mysql --host=database-1.ck1n4yzwola8 --user=admin --password=123456789 Validation < "$i";;
esac
printf 'waiting for import to finish\n'
done
- See
help case