$(cmd)
(command substitution) left unquoted in list contexts invokes the split+glob operator in POSIX shells like bash
. Here, you don't want the glob part. The split part splits on characters found in $IFS
(space, tab and newline by default).
So here, you'd want:
IFS='
' # split on newline only. Also IFS=$'\n' in bash/ksh93/zsh/mksh
set -o noglob # disable globbing
lines=($(df -k)) # use the split+glob operator
(note that it removes empty lines).
That also works with mksh
, yash
, ksh93
or zsh
(with zsh
you may omit the set -o noglob
, as zsh does only splitting, not globbing upon command substitution).
Alternatively, you could do (bash specific):
readarray -t lines < <(df -k)
Note that there's no guarantee that there will be one line per entry in the output of df
, and that doing text processing with shell loops is generally not the way to go. Also note that while array indices start at 0 in bash and ksh, they start at 1 in all other shells.