Reputation: 53
Current directory contains new logs that keep coming.
/tmp/logstash/ dir contains logs to which I will be comparing new ones
Conditions:
If the new log has the same name and the size that already exists in /tmp/logstash, I should get 'identical file already exists' msg.
Otherwise the script will move the new log to /tmp/logstash/.
Note, that if name is same but size is different, the script should still move new file to tmp/logstash/
My script is as follows and it's not working properly with with combining 'then && if', can you please help to fix it?
for file in *.log; do
new_filesize=$(du -b "$file" | cut -f 1)
if [[ -e /tmp/logstash/"$file" ]]
then
old_filesize=$(du -b /tmp/logstash/"$file" | cut -f 1) &&
if [[ "$new_filesize"="$old_filesize" ]]; then
echo "The file already exists"
fi
else mv $file /tmp/logstash
fi
done
Upvotes: 0
Views: 63
Reputation: 84559
Per your request in the comments. The following tests whether old_file
exists. If it does, it then checks whether the sizes between new_file
and old_file
differ. If they differ, then it moves new_file
to /tmp/logstash/
replacing old_file
. If old_file
exists and the files sizes are equal, then it will echo "The file already exists"
. In the event old_file
doesn't exist, then is simply copies new_file
to /tmp/logstash/
.
for file in *.log; do
if [ -e /tmp/logstash/"$file" ]; then
if [ $(stat %s "$file") -ne $(stat %s /tmp/logstash/"$file") ]
mv -f "$file" /tmp/logstash
else
echo "The file already exists"
fi
else
cp "$file" /tmp/logstash/"$file"
fi
done
Note: Remember quote your variables.
new_filesize
and old_filesize
for file in *.log; do
new_filesize=$(stat %s "$file")
if [ -e /tmp/logstash/"$file" ]; then
old_filesize=$(stat %s /tmp/logstash/"$file")
if [ $new_filesize -ne $old_filesize ]
mv -f "$file" /tmp/logstash
else
echo "The file already exists"
fi
else
cp "$file" /tmp/logstash/"$file"
fi
done
Note: mv -f
was added to all cases where old_file
exists to prevent move failure due to existing file.
Upvotes: 1
Reputation: 781096
You need spaces around the =
in the conditional expression:
if [[ $new_filesize = $old_filesize ]]; then
Without the spaces, you're just testing whether the concatenated string "$new_filesize"="$old_filesize"
is non-empty.
Upvotes: 2