Question

I'm working on a bash script to perform some mysqldump backups. I'n not very good at scripting.

I have:

#!/bin/bash
TNAMES="database1.tableA database2.tableD databaseN.tableZ"

I need to parse TNAMES to separate the database part from the table part to execute the mysqldump

for TABLE in $TNAMES
do
  mysqldump $OPTIONS $USER $PASSWORD $DB $TABLENAME > "some_file.sql"
  (some more actions here)
done

so in the first loop iteration the command will be:

mysqldump $OPTIONS $USER $PASSWORD database1 tableA > "some_file.sql"

Next:

mysqldump $OPTIONS $USER $PASSWORD database2 tableD > "some_file.sql"

Next:

  mysqldump $OPTIONS $USER $PASSWORD databaseN tableZ > "some_file.sql"

And so on.

Is there any easy way to do this with awk?

Was it helpful?

Solution 2

You can use "cut" for that:

for TABLE in $TNAMES
do
      DB=$(echo "$TABLE" | cut -d '.' -f 1)
      TABLENAME=$(echo "$TABLE" | cut -d '.' -f 2)
      mysqldump "$OPTIONS" "$USER" "$PASSWORD" "$DB" "$TABLENAME" > "some_file.sql"
done

OTHER TIPS

you don't need sed, awk or cut to perform simple prefix/suffix removal:

for spec in $TNAMES; do
  db=${spec%%.*}
  tb=${spec#*.}
  mysqldump ... $db $tb > $somewhere
done

Since your are initiating your variable in your bash you can use array:

Database[0]="database1"
Database[1]="database2"
...

Table[0]="tableA"
Table[1]="tableB"
...


# Loop over the table index
for i in $(seq 0 $((${#Database[@]}-1)))
do
   mysqldump $OPTIONS $USER $PASSWORD ${Database[$i]} ${Table[$i]} >> "some_file.sql"
done

I have take the liberty to happen to the file >> instead of creating a new file each time.

You could also use something like

#!/bin/bash

TNAMES="database1.tableA database2.tableD databaseN.tableZ"
for TABLE in "$TNAMES"
do
    while IFS='.' read DB TABLENAME
    do 
      mysqldump "$OPTIONS" "$USER" "$PASSWORD" "$DB" "$TABLENAME" > "some_file.sql"
    done <<<"$TABLE";
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top