2011-07-07 41 views
8

如果我在终端做ps ax,结果会是这样:回声ps,同时保留换行符?

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 

虽然如果我这样做echo $(ps ax),我得到:

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 

为什么?

如何保留换行符和制表符?

回答

25

一样:使用引号。

echo "$(ps ax)" 
2

这是因为echo根本不是管道 - 它将ps ax的输出解释为一个变量,而bash中的(未加引号的)变量实际上压缩了空白 - 包括换行符。

如果你想管的ps输出,然后用管道:一如既往

ps ax | ... (some other program) 
+0

好吧,说我想做'ps ax | grep foobar“它仍然混淆了设计。 – Tyilo

+0

我一直在使用这个构造,它对我很好。如果您认为实际管道输出不正确,请在您的问题中提供其他详细信息。 – Flimzy

+1

不,只是我很愚蠢 – Tyilo

0

或者,如果你想有一行接一行访问:

readarray psoutput < <(ps ax) 

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

这需要一个最近的(ISH)庆典版

5

中即变量只需使用双引号正在回显

echo "$(ps ax)" 

这样做不会造成额外的垃圾编码或麻烦。

编辑:呃...有人打我吧!大声笑

+0

Upvote for you too buddy。 –

-1

你在说什么管道的输出?你的问题说“管道”,但你的例子是一个命令替换:

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

更有用吗?

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

如果你在谈论command substitution,你需要报价为他人,以迫使外壳不扔掉的空白已经指出:

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

重新考虑你的问题/解决方案。

当您想要$(ps ax) - 保留换行符时 - USUALLY意味着设计不好,您可能需要使用管道或重定向。通常 - 所以,也许它是确定的 - 真正想知道你想达到什么。 :)