1

I would like to check the file check sums between 2 directories.

I have written the following script to do so:

#!/bin/bash

echo Checking File Copy

SRC_DIR=/home/user/src

echo Source Directory: $SRC_DIR

TGT_DIR=/media/user/tgt

echo Target Directory: $TGT_DIR

cd $SRC_DIR

for file_name in *.txt
do
 echo $file_name
 tgt_file=${file_name// /\\ }
 sum $TGT_DIR/$tgt_file
 sum $file_name
done

The script works fine until it encounters a file with space in the name at which point I get an error.

I tried to solve it by "escaping" the file name like so:

tgt_file=${file_name// /\\ }

Unfortunately that causes an error when reading the file names.

I have searched but have not found an answer that seems to work. Any suggestions would be very welcome. Thanks.

2 Answers2

3

You're not double-quoting any of your variables. Double-quoting your strings (including strings with variables) will cause them to be treated as a single token. Otherwise they will be treated as white-space delimited lists of tokens. This applies even if the white-space occurs after parameter-expansion - as is happening in your situation.

For further discussion on why this is important see the following post:

Here is what your script should probably look like:

#!/bin/bash

echo "Checking File Copy"

SRC_DIR="/home/user/src"

echo "Source Directory: ${SRC_DIR}"

TGT_DIR="/media/user/tgt"

echo "Target Directory: ${TGT_DIR}"

cd "${SRC_DIR}"

for file_name in *.txt
do
 echo "${file_name}"
 sum "${TGT_DIR}/${file_name}"
 sum "${file_name}"
done

You'll notice that I've quoted the strings as well as the variables. Strictly speaking this isn't really necessary here, but it's probably good to get in the habit of quoting everything that you want to consider as a single token.

I also used the curly-brace syntax for your variables. Again, this probably isn't necessary in this exact situation, but I would consider it a best-practice in general. For further discussion regarding the brace syntax see the following post:

igal
  • 9,886
0
diff -q <(ls -1 $dir1 | wc -l) <(ls -1 $dir2 | wc -l)

ls -1 gives you a list of files, 1 each line

wc -l count the lines

EDIT:

for file in $(sort -u <(ls -1 $dir1/; ls -1 $dir2/)); do echo $file; diff -q <(checksumcommand $dir1/$file) <(checksumcommand $dir2/$file); done
FaxMax
  • 726