hexaquark
hexaquark

Reputation: 941

Bash script backup, check if directory contains the files from another directory

I am making a bash backup script and I want to implement a functionality that checks if the files from a directory are already contained in another directory, if they are not I want to output the name of these files

#!/bin/bash

TARGET_DIR=$1
INITIAL_DIR=$2
TARG_ls=$(ls -A $1)
INIT_ls=$(ls -A $2)

if [[ "$(ls -A $2)" ]]; then
        if [[ ! -n "$(${TARG_ls} | grep ${INIT_ls})" ]]; then
                echo All files in ${INITIAL_DIR} have backups for today in ${TARGET_DIR}
                exit 0
        else 
                #code for listing the missing files
        fi
else
        echo Error!! ${INITIAL_DIR} has no files
        exit 1
fi

I have thought about storing the ls output of both directories inside strings and comparing them, as it is shown in the code, but in the event where I have to list the files from INITIAL_DIR that are missing in TARGET_DIR, I just don't know how to proceed.

I tried using the diff command comparing the two directories but that takes into account the preexisting files of TARGET_DIR.

In the above code if [[ "$(ls -A $2)" ]]; checks if the CURRENT_DIR contains any files and if [[ ! -n "$(${TARG_ls} | grep ${INIT_ls})" ]]; checks if the target directory contains all the initial directory files.

Anyone have a suggestion, hint?

Upvotes: 0

Views: 394

Answers (2)

Ohiovr
Ohiovr

Reputation: 977

rsync has a --dry-run switch that will show you what files have changed between 2 directories. Before doing rsync copies of my home directory I preview the changes this way to see if there could be evidence of mass mal encryption or corruption before proceeding.

Upvotes: 0

karakfa
karakfa

Reputation: 67477

you can use comm command

$ comm <(ls -A a) <(ls -A b)

will give you files in a only, both in a and b, and in only b in three columns. To get the list of files in a only for example

$ comm -23 <(ls -A a) <(ls -A b)

Upvotes: 1

Related Questions