Very new to scripting. I have a directory containing some text files and some with text files that also contain an additional extension (.xfr
) e.g. file1.txt
, file2.txt.xfr
, file3.txt
, file4.txt.xfr
.
Trying to write a bash script to check the directory, rename the file if it contains the .xfr
(removing the extension) and then write out log entries depending on the outcome.
I'm able to write a script to rename files but when it comes to the if
part, I'm struggling. Here is the bit that works:
#!/bin/bash
for file in ~/Test/Files/*.xfr
do
mv "$file" "${file%.xfr}"
echo "$file has been resent" > ~/Test/log.txt
done
To add the if
, I thought this would work but sadly not:
#!/bin/bash
if [[ ! -e ~/Test/Files/*.xfr ]]
then
mv "$file" "${file%.xfr}"
echo "$file has been renamed" > ~/Test/log.txt
else
echo "no files were renamed" ~/Test/log.txt
fi
Any assistance would be greatly appreciated.
Update: the script was updated to use varibales in place of the file path and so now looks like this:
#!/bin/bash
PATH='/home/davrog/Test/Files'
LOG='/home/davrog/Test/log.txt'
for file in $PATH/*.xfr
do
if [ -e $PATH/$file ]
then
mv "$file" "${file%.xfr}"
echo "$(date) $file has been resent"
else
echo "$(date) no files were stuck when check was run"
fi
done >>$LOG
This seems to have broken the mv function, I suspect because it is trying to rename the file back it it's current name. Looking at other posts, the mv function looks be be correct, so not sure how I can resolve that. Thanks in advance for any assistance.
file
– ilkkachu Jan 11 '19 at 11:58