3

I am writing a bash script, and on a condition I'd like to output ps aux --sort -rss

However, when I write :

echo `ps aux --sort -rss`

everything is on one huge line. How do I run it so it outputs like it normally does in a terminal?

  • 3
    Is there a reason you're not just running ps aux --sort -rss? – Michael Mrozek Nov 18 '11 at 19:09
  • @MichaelMrozek: I was using it in a script for a cron job. After you made your comment i probably could just call ps in the bash script and it would work as expected? I just edited my script and confirmed that it worked. +1 for your comment. I guess i'll use the accepted answer when i want to build and string and output it as one line – user4069 Nov 18 '11 at 20:29
  • If it does work fine without echo, somebody did submit that as an answer – Michael Mrozek Nov 18 '11 at 20:32
  • @MichaelMrozek yes but that doesnt answer my question. In this case i should be doing it that way but it still doesnt answer the question (if i accepted it, the title of the question would be misleading. But leave it please) – user4069 Nov 18 '11 at 20:38
8

Quote the command:

echo "`ps aux --sort -rss`"

Otherwise bash just parses the tokens, ignoring whitespace including newlines like it does when you type it by hand.

  • 1
    You're invoking a sub shell to issue a command that doesn't require a sub shell. – Paul Tomblin Nov 18 '11 at 19:48
  • 1
    @PaulTomblin I'm answering the question that was asked, how to get it to echo with the newlines. I don't know why he wants to do it this way, but it doesn't matter for correctly answering the question. – Kevin Nov 18 '11 at 20:01
  • @PaulTomblin if you -1 him can you please undo it – user4069 Nov 18 '11 at 20:22
  • 3
    Why should I undo it? It's the wrong way to get a ps result in the output of a bash script. Just because you accepted the answer doesn't make it right. – Paul Tomblin Nov 18 '11 at 20:27
  • 1
    Sometimes the right answer is "DON'T DO IT THE WAY YOU'RE ASKING HOW TO DO IT". Sometimes the people answering you know better than you do - that's why they're answering and you're asking. – Paul Tomblin Nov 18 '11 at 21:22
13

Get rid of the echo entirely, and just issue the command

ps aux --sort -rss

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy