开发者

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/Direc开发者_如何学JAVAtoryService 12 ?? Ss 0:26.93 /usr/sbin/notifyd

Why?

And how do I preserve the newlines and tab characters?


Same way as always: use quotes.

echo "$(ps ax)"


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


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)


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


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)"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜