Hi I want to create a bash file, where i define multiple files (the number is not set) and the script checks if a md5 hash for each file exist, and creates one if not? I am stuck with the if loop, how can I define a loop with variable length as a if condition?
COMPARE_FILES=("/folder/file1" "/folder2/file2" "file3" ... "/folderN/fileN")
for i in "${COMPARE_FILES[@]}"
do
base=${i%%.*} # does not work?
file=${##*/} # works as expected
if [ ! -f $COMPARE_DIR/compare/$base.md5 ]; then
rsync $COMPARE_LOC/"$i" $COMPARE_DIR/compare/ #works as expected
md5sum $COMPARE_LOC/$file > $COMPARE_DIR/$base.md5
rm $COMPARE_DIR/compare/$file #does not work
fi
done
I am not able to extract the filename and the base name from the array in the loop, can someone help me perhaps?
To get the basename from a filepath, use basename
:
$ i="/file/path/filename.ext"
$ base=$(basename $i)
$ echo $base
filename.ext
Then you can get the filename without extension as you were doing:
$ fnam=${base%.*}
$ echo $fnam
filename
Or the extension:
$ extn=${base#*.}
$ echo $extn
ext