11

I want to capture into my bash script (in a variable) the output of some command that prints its output to terminal. I have tried the following:

TEST_OUT=`the_command ARG1`   #Nope

#Putting the line "the_command ARG1" into a separate script, testing2.sh,

TEST_OUT=$(./testing2.sh)   #Nope

testing2.sh
TEST_OUT=$?  #Nope

I am 100% sure that when I run...

> the_command ARG1

...in a terminal, it prints to the terminal exactly the information I want to capture.

Thank you for any help!

5
  • 1
    Standard error output does not seem to be captured in your scripts so it will be printed to the terminal. Commented Aug 3, 2012 at 17:40
  • 1
    If the output is being sent to stderr, you'll need to redirect that to stdout before it can be capture in your var. Try TEST_OUT=$(the_command ARG1 2>&1) Commented Aug 3, 2012 at 17:42
  • Hey sorry, new to bash and scripting here... Are there 2 ways to print to terminal, stderr and stdout? Commented Aug 3, 2012 at 17:46
  • @ShawnChin Oh shit it worked! Nice! Post your answer and I'll accept that Commented Aug 3, 2012 at 17:49
  • 1
    posted. BTW, you generally print to terminal using stdout and only use stderr for error messages (so it doesn't get hidden when someone redirects the output to a file or var). For quick explanation of stdout and stderr, see en.wikipedia.org/wiki/…. Commented Aug 3, 2012 at 17:52

1 Answer 1

19

If the output is being sent to stderr, you'll need to redirect that to stdout before it can be capture in your var. Try:

TEST_OUT=$(the_command ARG1 2>&1)
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome I didn't know about the difference b/w stderr and stdout. Good stuff.
If you want only stderr, use $(the_command ARG1 2>&1 >/dev/null).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.