Getting output of shell command in bash array Getting output of shell command in bash array shell shell

Getting output of shell command in bash array


To build the associative array, try this:

declare -A proVarwhile read -r val key; do  proVar[${key#chr}]=$valdone < <(awk '{printf ("%s\t\n"), $1}' file.txt | grep -P 'pattern' | uniq -c)

Note: This assumes that your command's output is composed of multiple lines, each containing one key-value pair; the single-line output shown in your question comes from passing $proVar to echo without double quotes.

  • Uses a while loop to read each output line from a process substitution (<(...)).
  • The key for each assoc. array entry is formed by stripping prefix chr from each input line's first whitespace-separated token, whereas the value is the rest of the line (after the separating space).

To then create the bar plot, use:

while IFS= read -r key; do  echo "chr${key} $(printf '=%.s' $(seq $(( ${proVar[$key]} / 50 ))))"done < <(printf '%s\n' "${!proVar[@]}" | sort -n)

Note: Using sort -n to sort the keys will put non-numeric keys such as X and Y before numeric ones in the output.

  • $(( ${proVar[$key]} / 50 )) calculates the number of = chars. to display, using integer division in an arithmetic expansion.
  • The purpose of $(seq ...) is to simply create as many tokens (arguments) as = chars. should be displayed (the tokens created are numbers, but their content doesn't matter).
  • printf '=%.s' ... is a trick that effectively prints as many = chars. as there are arguments following the format string.
  • printf '%s\n' "${!proVar[@]}" | sort -n sorts the keys of the assoc. array numerically, and its output is fed via a process substitution to the while loop, which therefore iterates over the keys in sorted order.


You can create an array in an assignment using parentheses:

proVar=(`awk '{printf ("%s\t\n"), $1}' file.txt | grep -P 'pattern' | uniq -c`)

There's no built-in way to create an associative array directly from input. For that you'll need an additional loop.