Diogo Hartmann Diogo Hartmann - 1 year ago 46
Bash Question

Shell script foreach logic... Sending data to google drive with gdrive

i've made a small shell script to send some backup data to a google drive account... It's working fine, but i need to delete old files from google drive. I'm not good with shell script and i don't know how to finish the code below:


# Backing up to local folder
sudo gitlab-rake gitlab:backup:create

# Sending files to google drive https://github.com/prasmussen/gdrive
gdrive sync upload /path/to/backups folderID

# Delete 5 days older backups from local folder
find /path/to/backups/* -mtime +5 -exec rm {} \;

# Get date fom 5 days ago
DATA=`date +%Y-%m-%dT%H:%M:00 -d "5 days ago"`

The line below list all the files IDs i need to delete:

# List files to delete
gdrive list -q "'folderID' in parents and modifiedTime <= '$DATA-03:00'" --no-header | awk '{print $1;}'

Now I just need to run

gdrive delete <fileID>

for each id I listed before.

Can somebody help me with this foreach shell script thing?

Answer Source

Store the files into a variable (mostly for readability):

files=$(gdrive list -q ...)

Then set the IFS to empty so it strips all whitespace but the newline on each line:

IFS= read -r file; do
    printf 'gdrive delete %s\n' "$file"
done  <<EOF

I'm using a printf so you can see what the command will look like.

This is basically taken from the Bash FAQ.

Note that this changes the way bash interprets fields in character strings in your current shell.