I'm making a script to print ZFS filesystem info - currently in the testing phase, and I'm getting a strange error.
The relevant bit of my initial script is this:
zfs_human="$(zfs list | head -n 2 | tail -n 1)"
dfs_human="$(df -h | grep 'zfs' | head -n 1)"
zfs_usedh="$(echo $zfs_human | cut -d ' ' -f2)"
zfs_totah="$(echo $dfs_human | cut -d ' ' -f2)"
echo "$zfs_human"
echo "$dfs_human"
echo "$zfs_usedh"
echo "$zfs_totah"
Giving the following output:
zfs 2.31M 5.27T 34.4K /mnt/zfs
zfs 5.3T 128K 5.3T 1% /mnt/zfs
2.31M
5.3T
However, when I run shellcheck
, it says I should double-quote the variable names inside the command substitution, this is the output from shellcheck
:
In zfsspace.sh line 5:zfs_usedh="$(echo $zfs_human | cut -d ' ' -f2)" ^--------^
SC2086: Double quote to prevent globbing and word splitting.
Did you mean:
zfs_usedh="$(echo "$zfs_human" | cut -d ' ' -f2)"
In zfsspace.sh line 6:zfs_totah="$(echo $dfs_human | cut -d ' ' -f2)" ^--------^
SC2086: Double quote to prevent globbing and word splitting.
Did you mean:
zfs_totah="$(echo "$dfs_human" | cut -d ' ' -f2)"
Then I of course change my code to shellcheck's recommendation:
zfs_human="$(zfs list | head -n 2 | tail -n 1)"
dfs_human="$(df -h | grep 'zfs' | head -n 1)"
zfs_usedh="$(echo "$zfs_human" | cut -d ' ' -f2)"
zfs_totah="$(echo "$dfs_human" | cut -d ' ' -f2)"
echo "$zfs_human"
echo "$dfs_human"
echo "$zfs_usedh"
echo "$zfs_totah"
But now the output is this:
zfs 2.31M 5.27T 34.4K /mnt/zfs
zfs 5.3T 128K 5.3T 1% /mnt/zfs
Line 3 and 4 is blank, which means the 3rd and 4th command substitution does not work when following shellcheck's recommendation, but works when not quoting the variable that I echo.
I'm using Bash 5.0.17 on Ubuntu 20.04.1
Can anyone explain this please??? Thanks.
$zfs_human
is subject to split+glob, as a result of which sequences of whitespace are replaced with the first character of the currentIFS
(by default, a single space). The quoted"$zfs_human"
will retain whatever whitespace is output by thezfs list
command. You could likely avoid the issue by usingawk
(which treats contiguous whitespace as the delimiter by default) instead ofcut -d ' '
– steeldriver Sep 27 '20 at 20:27... | sed -n 2p
– bac0n Sep 28 '20 at 5:37read -r filesystem size used avail _ < <(df -hP | grep -m1 zfs)
... read will squeeze spaces for you. – bac0n Sep 28 '20 at 5:49