I need to find amount of free disk space on a RAM disk in a portable script (not GUI, not anything distro-specific). The df utility does the job, but it spews quite a lot of output so I have to fish it out, like:

df -P /tmp | tail -n 1 | awk '{print $4; }'

Tried also stat but cannot figure how to specify a 'filesystem' to it. Even when tmpfs is mounted on /tmp, stat "%f" /tmp interprets /tmp as a file, not as a filesystem.

Is there a better way?

(No this is not a duplicate for 'how to find free disk space and analyze usage'. Thank you for being so vigilant)

  • The way you do it is the way to go. You've a oneliner that does what you need (with only 3 commands), not sure why you look for a shorten way. – Chen A. Jul 26 '17 at 14:33
  • Thanks @Vinny. I'm not expert in Unix, thought there's something obvious I'm missing. And would like to minimize dependency on other things (tail,awk). – ddbug Jul 26 '17 at 14:36
  • 1
    For the filesystem information on /tmp, use stat -f /tmp. You'd still need some massaging of the output if you want a single number. – user4556274 Jul 26 '17 at 14:37
  • A compatible way would be to use read -d '' -ra df_arr < <(LC_ALL=C df -P /tmp); echo "${df_arr[11]}" See mywiki.wooledge.org/BashFAQ/094?highlight=%28disk%29 – Valentin Bajrami Jul 26 '17 at 14:37
  • @ddbug I think your solution is good, simple and readable. You should stick to it. with stat -f /tmp you still need to do manipulations, stat -f /tmp | grep 'Free' | head -n 1 | awk '{ print $5 }'. Looks less efficient if you ask me – Chen A. Jul 26 '17 at 14:44

From the man page for stat(1)

-f, --file-system
display file system status instead of file status

So to pull the free blocks of the filesystem on which /tmp is located, you could try something like

stat -f /tmp -c "%f"

Or, to get the value in octets, multiply free blocks by blocksize:

stat -f /tmp -c "%f*%S" | bc
  • Perfect! except that bc is not available on my system ,so echo $(( $(stat -f /tmp -c "%f*%S") )) – ddbug Jul 26 '17 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.