Kupe3
Kupe3

Reputation: 411

check if find command return something (in bash script)

i have the following bash script on my server:

today=$(date +"%Y-%m-%d")
find /backups/www -type f -mtime -1|xargs tar uf /daily/backup-$today.tar

as you can see it creates backups of files modified/created in the last 24h. However if no files are found, it creates corrupted tar file. I would like to wrap it in if..fi statement so id doesn't create empty/corrupted tar files.

Can someone help me modify this script?

Thanks

Upvotes: 2

Views: 9323

Answers (4)

tripleee
tripleee

Reputation: 189397

xargs -r does nothing if there is no input.

Upvotes: 0

twalberg
twalberg

Reputation: 62379

One relatively simple trick would be this:

today=$(date +"%Y-%m-%d")
touch /backups/www/.timestamp
find /backups/www -type f -mtime -1|xargs tar uf /daily/backup-$today.tar

That way you're guaranteed to always find at least one file (and it's minimal in size).

Upvotes: 0

Pilou
Pilou

Reputation: 1478

You can check if result is ok then check if result is empty :

   today=$(date +"%Y-%m-%d")
   results=`find /backups/www -type f -mtime -1`


    if [[ 0 == $? ]] ; then
     if [[ -z $results ]] ; then
      echo "No files found"
     else
      tar uf /daily/backup-$today.tar $results
     fi
    else
     echo "Search failed"
    fi

Upvotes: 7

John Kugelman
John Kugelman

Reputation: 361615

find /backups/www -type f -mtime -1 -exec tar uf /daily/backup-$today.tar {} +

Using -exec is preferable to xargs. There's no pipeline needed and it will handle file names with spaces, newlines, and other unusual characters without extra work. The {} at the end is a placeholder for the file names, and + marks the end of the -exec command (in case there were more arguments to find).

As a bonus it won't execute the command if no files are found.

Upvotes: 2

Related Questions