1

I am building a script to back-up files and directories in my linux. These backups are stored in the map Archive.

Now i use in my source a specific directory but i have e.g.

input.txt with these directories:

/Downloads
/etc/var

or also with specific files

/etc/log/test.txt

Using /Downloads or /etc/var it must also backup the subdirectories of these directories. E.g. /Downloads has 3 other directories /dir1,/dir2,/dir3 these need to be archived also.

How can i use that file input.txt as source? Of the whole input.txt file I have to make 1 archive.

#!/bin/sh

source="/Downloads"     
archive="example.tgz"       
dest="Archive"              
path="input.txt"                

tar czf $dest/$archive $source

ls $dest

#this is how i read my file
while read line
    do
        echo $line
done < $path
LinuxWar
  • 21
  • 5

2 Answers2

1

Using tar for creating an archive -T option can be used to take files from an input file.

input.txt:

/Downloads
/etc/var
/etc/log/test.txt

script:

#!/bin/sh

archive="example.tgz"       
dest="Archive"              
path="input.txt"                

tar czf $dest/$archive -T $path
Kadir
  • 1,664
  • 2
  • 19
  • 22
0

You can do it like this:

#!/bin/bash

output_dir="/tmp/snapshots"
current_date="$( date +%F_%H-%M-%S )"
script_name="$( basename $0 )"

dirs=""

while IFS='' read -r line || [[ -n "$line" ]]; do
    # directory exists?
    if [ -d "$line" ] || [ -f "$line" ]; then
        dirs="$dirs $line"
    else
        echo "${script_name}: cannot access $line. No such directory. Skip"
    fi
done < "$1"

output_file="${output_dir}/${current_date}.tar.gz"

if [ -n "$dirs" ] ; then
    tar -czvf $output_file $dirs
    echo "${script_name}: done!"
    exit 0
else
    echo "${script_name}: operation failed. Cannot create an empty archive."
fi

First, this script specifies a directory (/tmp/snapshots in my case) where a resulting archive will be saved. Current date is used as a name to make sure you do not accidentally overwrite you previous archive.

Next you read you input file line by line, appending directory or file names to the $dirs variable if and only if they acrually exist in your filesystem. See this thread for more details about what's going on in the while loop.

Then, if your $dirs variable is not empty (i.e. at least one directory or file exists), you're creating an archive, quitting otherwise.

Not save the script (say, as snapshot.sh), make it executable ($ chmod +x snapshot.sh) and run like this:

./snapshot.sh input.txt
vrs
  • 1,922
  • 16
  • 23