I am trying to read "df -h" output as array of lines in shell script.

I tried the below code, but its var[0] is giving me the first column of first line instead of the whole first line. My expectation is to get the complete line in one iteration.

var=($(df -k))
echo " echo ${var[0]}

How can I achieve this without using awk?

  • Can you clarify which shell you're working in?
    – Jeff Schaller
    Mar 1, 2016 at 11:07
  • i am using bash Mar 1, 2016 at 11:11

1 Answer 1


$(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:

' # 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.

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.