Bash: Command output to array of lines 2018-05-10

We had a case at work were multi-line output of a command should be turned into an array of lines. Here’s one way to do it.

Two Bash features take part with this approach:

  • $'....' syntax (a dollar right in front of a single-tick literal) activates interpolation of C-like escape sequences (see below)
  • Bash variable IFS — the internal field separator affecting the way Bash applies word splitting — is temporarily changed from default spaces-tabs-and-newlines to just newlines so that we get one array entry per line

Let me demo that:

# f() { echo $'one\ntwo  spaces' ; }

# f
one
two  spaces

# IFS=$'\n' lines=( $(f) )

# echo ${#lines[@]}
2

# echo "${lines[0]}"
one

# echo "${lines[1]}"
two  spaces
Leave a Reply

You must be logged in to post a comment.