0
votes

I'm trying to create a script that will do the following:

  1. create /home/testuser/backup as a directory if it doesn't exist (and won't show an error message if it does exist)
  2. obtain the current date and store it as a variable
  3. Using Tar:
    • backup the entire projectfiles directory
    • backup is compressed, in gzip format, in archive format
    • uses the stored variable to include the date in the tar filename
    • the backup goes to the /home/testuser/backup directory
    • create a log file called testuser.log with all messages generated by the tar command (using verbose mode)
    • save the log file in /home/testuser/backup/testuser.log

I'm having trouble with the command syntax and I don't quite understand what I'm doing wrong.

cd /home/testuser

mkdir -p /home/testuser/backup

today=$(date'+%d-%m-%y')

tar -zcvf testuserbackup-$today.tar.gz projectfiles && 
testuserbackup-$today.tar.gz /home/testuser/backup

testuserbackup-$today.tar.gz >> testuser.log 2>/dev/null

mv testuser.log /home/testuser/backup

When I try to run the script I get the following terminal output:

./script2.sh: line 6: date+%d-%m-%y: command not found
projectfiles/
projectfiles/budget/
projectfiles/budget/testuserbudget1.txt
projectfiles/budget/testuserbudget2.txt
projectfiles/old/
projectfiles/old/testuserold2.txt
projectfiles/old/testuserold1.txt
projectfiles/documents/
projectfiles/documents/testuserdoc2.txt
projectfiles/documents/testuserdoc1.txt
./script2.sh: line 7: testuserbackup-.tar.gz: command not found

I'm open to any suggestions. This task is from an old assignment from last semester that I'm revisiting for fun... According to my old assignment notes this task should be able to be done in no more than 4 lines of code.

**EDIT:**Finished script (with assistance of John)

#!/bin/bash
mkdir -p /home/testuser/backup
today=$(date '+%d-%m-%y')
tar -zcvf backup/testuserbackup-"$today".tar.gz projectfiles > 
backup/testuser.log 2>&1
1

1 Answers

0
votes

You're missing a space:

today=$(date '+%d-%m-%y')
#           ^

Additionally, these lines should all be combined:

tar -zcvf testuserbackup-$today.tar.gz projectfiles && 
testuserbackup-$today.tar.gz /home/testuser/backup

testuserbackup-$today.tar.gz >> testuser.log 2>/dev/null

mv testuser.log /home/testuser/backup

The log file needs to be created in the same line as the tar command, and making the tarball and the log file show up in the right location can be done by writing out their full paths. That gets rid of the need to move them later.

tar -zcvf backup/testuserbackup-"$today".tar.gz projectfiles > backup/testuser.log 2>&1

It's a good idea to capture stderr as well as stdout, so I changed 2>/dev/null to 2>&1.