Reputation: 9029
Still learning bash but I had some questions in regards to my script.
My goal with the script is to access a folder with jpg images and if an image is 34.9kb it will return file not present. 34.9kb is the size of the image that shows "image not present".
#!/bin/bash
#Location
DIR="/mnt/windows/images"
file=file.jpg
badfile=12345
actualsize=$(du -b "$file" | cut -f 1)
if [ $actualsize -ge $badfile ]; then
echo $file does not exist >> results.txt
else
echo $file exists >> results.txt
fi
I need it to print each line to a txt file named results. I did research where some people either suggested using du -b
or stat -c '%s'
but I could not see what the pros and cons would be for using one or the other. Would the print to file come after the if else or stay with the if since Im printing for each file?? I need to print the name and result in the same line. What would be the best way to echo the file??
Upvotes: 1
Views: 879
Reputation: 87004
Based on your question and your comments on your following question I'm assuming what you want to do is:
If my assumptions are close, then this should get you started:
# Location
DIR="/home/lsc"
# Size to match
BADSIZE=40318
find "$DIR" -maxdepth 1 -name "*.jpg" | while read filename; do
FILESIZE=$(stat -c "%s" "$filename") # get file size
if [ $FILESIZE -eq $BADSIZE ]; then
echo "$filename has a size that matches BADSIZE"
else
echo "$filename is fine"
fi
done
Note that I've used "find ... | while read filename
" instead of "for filename in *.jpg
" because the former can better handle paths that contain spaces.
Also note that $filename
will contain the full path the the file (e.g. /mnt/windows/images/pic.jpg
). If you want to only print the filename without the path, you can use either:
echo ${filename##*/}
or:
echo $(basename $filename)
The first uses Bash string maniputation which is more efficient but less readable, and the latter does so by making a call to basename
.
Upvotes: 1
Reputation: 200573
stat -c '%s'
will give you the file size and nothing else, while du -b
will include the file name in the output, so you'll have to use for instance cut
or awk
to get just the file size. For your requirements I'd go with stat
.
Upvotes: 2