简体   繁体   中英

how to find the amount of space in a directory or the partition directory is in

I want to write a script that fills a directory with music until there's a certain amount of space left. The directory may be on various partitions and I don't know how to ask a directory for free space or it's partition.

pseudocode
fill(directory)
  until < 100 mb of free space in directory
    copy music to directory

How would you do it using unix tools like bash, find, etc.

Linux's df will tell you exactly that. To find the free space on the volume a folder resides in, execute:

df -h /home/chris/directory

Output:

Filesystem            Size  Used Avail Use% Mounted on 
server:/vol/home      2.0T  1.3T  759G  63% /home/chris

Omit the -h flag to get raw bytes instead of the human-readable K/M/G/T.

EDIT Just because I'm bored, I went ahead and wrote a script for you:

#!/bin/bash
fillDir='/mnt/fillMe'
musicFile='/home/chris/Yakety Sax.mp3'

while [ `df -P "$fillDir" | awk 'NR==2{print $4}'` -gt 100000000 ]
do
  echo `df -Ph "$fillDir" | awk 'NR==2{print $4}'` space left.
  cp "$musicFile" "$fillDir"
done

I assume you mean you have a specific directory, on a specific partition that you wish to fill until there is only 100 MB left.

The df command will return the amount of disk space left on a given directory's disk/partition.

df musicfolder/

The fourth column will give free space

Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda1            151733412  24153792 119871924  17% /

you can use awk to gain the fourth column value and ignore the headers. So your script will be something like:

freespace=$(df /musicfolder | awk 'FNR>1{print $4}')

while [ $freespace -gt 10000000 ] ; do
    (copy files from wherever)
    freespace=$(df ~/musicfolder | awk 'FNR>1{print $4}')
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM