4

I have this variable in a bash script on ubuntu 12.04 which is set to show the available MB on the root partition:

AV_MB=$(df -m |awk NR==2 |awk '{print $4}')

Is there an elegant way to combine these two awk expressions into one? Or a shorter way with sed or grep or cut?

  • 1
    LIke: df -m | awk 'NR==2{print $4}'? awk '$NF=="/" {print $4}' is more robust... – jasonwryan Mar 31 '16 at 7:43
  • Yeap, thanks. It's one of those questions where you spend an hour googling and are then embarrassed when faced with the simple, sweet solution. Please post this as an answer so I can mark it as correct – Nahshon paz Mar 31 '16 at 7:46
  • 2
    @Nahshonpaz df has the --output flag that can be very useful in such situations. e.g df -m / --output=avail |tail -n1 or if you want to use awk df -m / --output=avail |awk 'getline' And if you want to use purely bash syntax: read -d '' -ra df_arr < <(LC_ALL=C df -mP /); echo "${df_arr[10]}" – Valentin Bajrami Mar 31 '16 at 7:57
  • 1
    neat @val0x00ff , I'll check it out – Nahshon paz Mar 31 '16 at 8:02
9

Awk works on the "pattern {action}" model, so you can combine those two processes into a single and correct:

 df -m | awk 'NR==2 {print $4}'

This, however, is fragile as the second record could change (on my systems, the root record is the third row), so you can match on the final field of the record for the root filesystem, like so:

df -m | awk '$NF == "/" {print $4}'

which ensures your pattern matches wherever df prints /.

  • That's a useful tip, with $NF. Cheers – Nahshon paz Mar 31 '16 at 7:51
  • Shouldn't $NF be equal to a number, what does it mean when it equals "/"? – Josh Rumbut Mar 31 '16 at 19:23
  • @JoshRumbut $NF is a special awk variable that means the final field of a record. – jasonwryan Mar 31 '16 at 19:40
  • 2
    I get it now, NF is the number of fields and $NF is the value of the NFth field. – Josh Rumbut Mar 31 '16 at 19:50
6

Since you know what partition you are looking for, just specify it in the df command:

df -m /

Also, you can use the --output option to define what columns you want to show. In this case, "available", whic

df -m --output=avail /

From man df:

--output[=FIELD_LIST]

use the output format defined by FIELD_LIST, or print all fields if FIELD_LIST is omitted.

...

FIELD_LIST is a comma-separated list of columns to be included. Valid field names are: 'source', 'fstype', 'itotal', 'iused', 'iavail', 'ipcent', 'size', 'used', 'avail', 'pcent' and 'target' (see info page).

Note, however, that this --output option may be just available in GNU. Also, it prints the header, so you may want to pipe to tail -1 to get the last line.

  • unfortunately on ancient ubuntu 12.04, df: unrecognized option '--output=avail' :-( – Nahshon paz Mar 31 '16 at 10:19

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.