Backup directories with space in directory name

Karl Auer kauer at biplane.com.au
Sat Dec 31 05:12:18 UTC 2016


On Fri, 2016-12-30 at 21:47 -0600, Jack McGee wrote:
> I am trying to use this perl script to backup a directory, but it
> fails with this error:

You need to protect every expansion point with one set of quotes.

> # What to backup.
> backup_files="/mnt/ntfs-d/My Documents"

That's good. That will keep the path safe *within this script*.
However, the variable name is poor, since the value is not a list of
files, the value is the name of a directory containing files to back
up. Suggest something like "directory_to_back_up".

BTW, if you ever want to put more than one directory name into that
variable, you will need to do more work than described here.

> # Where to backup to.
> dest="/mnt/media3/backups/desktop"

Ditto. Not strictly necessary here, because the variable value contains
no spaces. It's still good practice, though, in case you ever change
that and forget the quotes.

> # Setup variables for the archive filename.
> day=$(date +%A)
> hostname=$(hostname -s)

I'm ignoring all that stuff, but check with debug statements that it
doesn't generate filenames with spaces in them, or wrap them in quotes
if it does. From the example filename you gave it looks like this is
not doing what you want it to, but that's a different problem :-)

> # Print start status message.
> echo "Backing up $backup_files to $dest/$archive_file"

No need for protection here, since it's all grist to echo's mill. You
might like to do this though, just for the look of it:

   echo "Backing up $backup_files to \"$dest/$archive_file\""

> # Backup the files using tar.
> tar czf $dest/$archive_file $backup_files

That last line is where it all goes to heck. The script will blindly
substitute the variable values into that command line, so what you get
when you do the above is (all on one line really, but split here for
effect):

   tar
   czf
   /mnt/media3/backups/desktop/jmcgee-desktop-Friday.tgz
   /mnt/ntfs-d/My
   Documents

I.e., tar sees separate arguments on either side of any spaces. You
need to wrap your concatenated variables in double quotes:

   tar czf "$dest/$archive_file" "$backup_files"

> # Long listing of files in $dest to check file sizes.
> ls -lh $dest/

For safety, I'd do the same there, just in case $dest ever grows some
embedded spaces. I.e.:

   ls -lh "$dest"

What do you mean "check file sizes"? There doesn't seem to be any
checking in your script.

Regards, K.

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au)
http://www.biplane.com.au/kauer
http://twitter.com/kauer389

GPG fingerprint: A52E F6B9 708B 51C4 85E6 1634 0571 ADF9 3C1C 6A3A
Old fingerprint: E00D 64ED 9C6A 8605 21E0 0ED0 EE64 2BEE CBCB C38B






More information about the ubuntu-users mailing list