Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying files while there is enough space in linux bash script

Tags:

linux

bash

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.

like image 603
igor.sol Avatar asked Sep 05 '25 03:09

igor.sol


1 Answers

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" 
like image 86
Inian Avatar answered Sep 07 '25 21:09

Inian