Backup script in bash

Asked by At

I need to write a script that will look for all files with the suffix ~ (eg file.txt ~) in current directory. If the script will find something, it should be copied to BACKUP directory.

If the BACKUP directory does not exist, the script should create it. If there is already a file (or other non-directory) named BACKUP, the script should report an error.

The problem is that on line if [ $x -eq BACKUP.* ];. Bash shows if [ $x -eq BACKUP.* ];

Appreciate any help

#!/bin/bash
if [ ! -d BACKUP ]; 
then
    mkdir BACKUP;
fi
for x in *. *~ ; do
    if [ $x -eq BACKUP.* ]; 
    then
        echo "Error, file BACKUP exist";
    else
        cp ./$x ./BACKUP;
    fi
done

1 Answers

1
Community On

You mean something like that?

#!/bin/bash

BACKUP=./BACKUP

if [[ -e "$BACKUP" ]]; then
    echo "$BACKUP already exists!" >&2 
    exit 1
fi

mkdir "$BACKUP"
find . -maxdepth 1 -type f -name "*~" -exec cp {} "$BACKUP" \;