Bash – Why does a Bash ‘while’ read loop with a command substitution herestring not read the entire input

bashcommand-substitutionhere-stringread

Look at this very basic Bash script:

#!/bin/bash
while read l
do
  echo $l
  echo "next one"
done <<< $(ps aux)

I have several processes on my computer, and the ps aux command works fine in the terminal.

I only get one iteration in the loop and ps command output is given on the same line. Why doesn't it work as intended?

Best Answer

In bash versions < 4.4-beta you need to add double quotes:

#!/bin/bash
while read l
do
  echo $l
  echo "next one"
done <<< "$(ps aux)"

See:


In general, I think it is better to use process substitution:

#!/bin/bash
while read l
do
  echo $l
  echo "next one"
done < <(ps aux)

(To avoid issues, you might want to use IFS=).

or even better, use a program specialized for reading files or input line by line like e.g. awk.

ps aux | awk '{print $0; print "next one"}'
Related Question