Tyilo
Tyilo

Reputation: 30102

Echo ps while preserving newlines?

If I do ps ax in Terminal, the result will be like this:

  PID   TT  STAT      TIME COMMAND
    1   ??  Ss     2:23.26 /sbin/launchd
   10   ??  Ss     0:08.34 /usr/libexec/kextd
   11   ??  Ss     0:48.72 /usr/sbin/DirectoryService
   12   ??  Ss     0:26.93 /usr/sbin/notifyd

While if I do echo $(ps ax), I get:

PID TT STAT TIME COMMAND 1 ?? Ss 2:23.42 /sbin/launchd 10 ?? Ss 0:08.34 /usr/libexec/kextd 11 ?? Ss 0:48.72 /usr/sbin/DirectoryService 12 ?? Ss 0:26.93 /usr/sbin/notifyd

Why?

And how do I preserve the newlines and tab characters?

Upvotes: 23

Views: 17619

Answers (5)

David W.
David W.

Reputation: 107040

Are you talking about piping the output? Your question says "pipe", but your example is a command substitution:

ps ax | cat  #Yes, it's useless, but all cats are...

More useful?

ps ax | while read ps_line
do
   echo "The line is '$ps_line'"
done

If you're talking about command substitution, you need quotes as others have already pointed out in order to force the shell not to throw away whitespace:

echo "$(ps ax)"
foo="$(ps ax)"

Upvotes: -1

Jason
Jason

Reputation: 193

Simply use double-quotes in the variable that is being echo'd

echo "$(ps ax)"

this will do it without all that extra junk coding or hassle.

edit: ugh... someone beat me to it! lol

Upvotes: 10

sehe
sehe

Reputation: 392931

Or if you want to have line-by-line access:

readarray psoutput < <(ps ax)

# e.g.
for line in "${psoutput[@]}"; do echo -n "$line"; done

This requires a recent(ish) bash version

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798616

Same way as always: use quotes.

echo "$(ps ax)"

Upvotes: 54

Jonathan Hall
Jonathan Hall

Reputation: 79576

That's because echo isn't piping at all--it's interpreting the output of ps ax as a variable, and (unquoted) variables in bash essentially compress whitespace--including newlines.

If you want to pipe the output of ps, then pipe it:

ps ax | ... (some other program)

Upvotes: 3

Related Questions