1

Create a script to backup a file or directory tree by making a zip of the file(s) and copying it $HOME/Backups. The zipfile name should include what it is backing up, and the date the file was created. The script should take a random number of arguments specifying what to backup. If it is not given at least one item to include in the backup, it should complain. Ive got most of it to work but im having issues with multiple files ie file1 file2 to backup at the same time

#!/bin/bash
clear
echo
echo "Use this script to backup files to your home/backups directory"
echo
ls -la
echo
echo "================================================================"
echo
echo -n "Input file(s)/dir to backup: " ; read filez

while [ "$filez" == "" ] ; do
    echo -n "You didnt input a filename, try again: " ; read filez
done

while [ ! -e  "$filez" ] ; do
    echo -n "No such file/dir, try again: " ; read filez
    while [ "$filez" == "" ] ; do
        echo -n "You didnt input a filename, try again: " ; read filez
    done
done


echo
echo "================================================================"
echo
echo -n "Input name of backup file you wish to create(date automatically included): " ; read filezname
while [ "$filezname" == "" ] ; do
    echo -n "You didnt input a filename, try again: " ; read filezname
done

zip -r $HOME/backups/$filezname"_$(date +%F)" $filez
1

1 Answer 1

0

Personally, I'm a fan of bash scripts taking arguments right from the command line:

script arg1 arg2 arg3 ...

Bash takes arguments using the special array $@, and you can do arguments processing with shift. Something like this:

#!/bin/bash

filezname=$1
shift

filez=""
for file in "$@"
do
    filez="$filez $file"
done

if [[ $filez == "" ]]
then
    echo "Give me argz! Nom nom nom!"
    exit 0
fi

# Do stuff

What this does is it takes the first argument, takes it as the name of the zip file, and then slurps the rest of the filenames you want to zip up into a big long space-separated string that you can play with.

1
  • You can't robustly build a list of arguments in single string $filez - use an array instead (or simply use "$@" directly).
    – mklement0
    Apr 6, 2016 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.