bash 在保留换行符的同时回显 ps?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6615966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Echo ps while preserving newlines?
提问by Tyilo
If I do ps axin Terminal, the result will be like this:
如果我ps ax在终端中执行,结果将是这样的:
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:
如果我这样做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
Why?
为什么?
And how do I preserve the newlines and tab characters?
以及如何保留换行符和制表符?
回答by Ignacio Vazquez-Abrams
Same way as always: use quotes.
与往常一样:使用引号。
echo "$(ps ax)"
回答by Jason
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
编辑:呃……有人打败了我!哈哈
回答by Flimzy
That's because echoisn't piping at all--it's interpreting the output of ps axas a variable, and (unquoted) variables in bash essentially compress whitespace--including newlines.
那是因为echo根本不是管道——它将 的输出解释ps ax为变量,而 bash 中的(未加引号的)变量基本上压缩了空格——包括换行符。
If you want to pipe the output of ps, then pipe it:
如果要通过管道传输 的输出ps,则通过管道传输:
ps ax | ... (some other program)
回答by sehe
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
这需要最近的(ish)bash 版本
回答by David W.
Are you talking about pipingthe 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:
如果你在谈论命令替换,你需要引号,正如其他人已经指出的那样,以强制 shell 不丢弃空格:
echo "$(ps ax)"
foo="$(ps ax)"

