I want to create simple bash script which will copy data files from source directory to tmpfs ramdrive. I need this script to be time-effective so it is not an option to try to do copy and check result code of copy command ( I assume copy command will start copying and fail only when there is no space. I want to avoid starting copy when there is not enough space). Here is pseudocode:
for filename in /data/*.dat; do
bname="$(basename $filename)"
ramname="/ramd/$bname"
if there is not enough space for $filename on ramdrive then
break
cp $filename $ramname
done
Can you please suggest a replacement for the if-break statement.
You can do this with POSIX
defined options for df - report free disk space and du - estimate file space usage, the former with the -P
flag for reporting the free space available on the system and parsing out only block size with awk
and doing the same for the file with the -k
flag in du
.
availMem=$(df -P "$ramname" | awk 'END{print $4}')
fileSize=$(du -k "$filename" | awk '{print $1}')
if (( fileSize > availMem )); then
break
fi
(or) a POSIX
-ly integer comparison without bash
as
if [ "$fileSize" -gt "$availMem" ]; then
break
fi
You can also throw in a printf
just before the break
for a debug purose,
printf "Requesting %s for copy when there is only %s left\n" "$fileSize" "$availMem"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With