Issue
I am writing a script which will be used to gather information on the available and used space on different partitions across servers. I need to be able to capture the output as a variable.
For example, if the output looked like:
Filesystem Size Used Avail Use% Mounted on
devtmpfs 2.9G 0 2.9G 0% /dev
tmpfs 2.9G 4.0K 2.9G 1% /dev/shm
tmpfs 2.9G 488K 2.9G 1% /run
tmpfs 2.9G 0 2.9G 0% /sys/fs/cgroup
/dev/mapper/vg_os-lv_root 3.9G 1.6G 2.1G 44% /
How could I capture 2nd row Used, Avail and Mounted on as variables?
Solution
I use a general way for things like that: for capturing a line, I use grep
in case of a keyword, or a combination of head
and tail
in case of a line number. Then, I use awk
for getting a certain column.
In this case, you get something like:
var_used=$(df -hk | grep "/dev/shm" | awk '{print $3}')
var_avail=$(df -hk | grep "/dev/shm" | awk '{print $4}')
var_mounted=$(df -hk | grep "/dev/shm" | awk '{print $6}')
In case you're interested in the "/dev" one, you need to grep on /dev$
(the dollar sign stands for "end-of-line").
For your information: I've mentioned the head
and tail
usage, but I don't show exactly how it works, for the simple reason: you seem to be interested in one particular line (like the "/dev" one), which currently is at the first line of your output. If, for any reason, this line number changes, you might need to rework your script, but using the "grep" approach this problem won't occur.
Answered By - Dominique Answer Checked By - Katrina (WPSolving Volunteer)