1

I have this bash script, but it doesn't seem to work at the 'find' point.

#!/bin/bash
echo 'What date YYYY-MM-DD format?'

read date

echo "starting restore script..."
echo "Looking in /root/backups/dbback_$date/"

cd "/root/backups/dbback_$date/"

echo 'What search term for files?'

read search

echo 'What database am I restoring too?'

read database

count=`ls -l | grep "$search" | wc -l`
echo "$count files found containing $search"

find "/root/backups/dbback_$date/" -type f -name '$search*.sql.gz' -not -path '*livefiles*' | while read file; do
echo "$file is being restored"
gunzip < "$file" | mysql -u root -p* '$database';
echo "$file has been restored...moving on to next file."
done

Between the find and the done - nothing happens, the last echo I get is

9 files found containing test

Please can anyone advise if I am doing something wrong?

DISMFA
  • 33
  • 5
  • 2
    in `'$search*.sql.gz'` the shell will not expand `$search` because of the surrounding single quotes – steeldriver Oct 29 '20 at 14:15
  • And read [this answer about `read`](https://unix.stackexchange.com/a/209184/108618). – Kamil Maciorowski Oct 29 '20 at 14:23
  • Thank you for your help, @steeldriver - can I achieve $search*.sql.gz within quotes? As without the quotes I get the error `paths must precede expression: ` – DISMFA Oct 29 '20 at 14:23
  • Thank you @KamilMaciorowski - I have adjusted this now to `| while IFS= read -r line; do` – DISMFA Oct 29 '20 at 14:26
  • 2
    @DISMFA you should keep the shell glob `*` inside quotes to prevent the shell from expanding *that* ex. `$search'*.sql.gz'` or use double quotes `"$search*.sql.gz"` – steeldriver Oct 29 '20 at 14:27
  • Thank you so much. Got it all working - I actually ended up doing "${search}*.sql.gz" before I saw your comment - but this has got it working too. Appreciate it. – DISMFA Oct 29 '20 at 14:33

1 Answers1

1
find "/root/backups/dbback_$date/" -type f -name "${search}*.sql.gz" -not -path '*livefiles*' | while IFS= read -r file; do
echo "${file} is being restored"
gunzip < "${file}" | mysql -u root -p* $database;
echo "${file} has been restored...moving on to next file."
done

Now works

DISMFA
  • 33
  • 5