pcdinh
pcdinh

Reputation: 666

Bash's echo statement makes it impossible to capture command output of a subsequent statement

I got into a very strange situation (to me) when an echo statement can prevent me from getting standard out message from an subsequent command

This is my test.py:

print "Test Only"

This is my test.sh:

start() {
    # Sample code to make sure that code within the if .. fi is executed
    if [ 1 -eq 1 ]; then
        echo "Start server"
        /usr/bin/python test.py
    fi; 
}

start

Actual output when executing /bin/bash test.sh:

Start server

Expected output:

Start server

Test Only

My solution (workaround):

If I comment out the line echo "Start server", I can get the message Test Only as usual.

My conclusion is that echo statement makes something wrong here. But it is out of my knowledge. Could you help me to understand why this can happen.

Another solution:

start() {
    # Sample code to make sure that code within the if .. fi is executed
    if [ 1 -eq 1 ]; then
        MSG1="Start server"
        MSG2=`/usr/bin/python test.py`
        echo $MSG1
        echo $MSG2
    fi; 
}

Updated

Thank to @ghoti, I have solved my issue: there may be some invisible characters in my code. Eliminating them all and it works now

Upvotes: 0

Views: 1232

Answers (3)

Edward Loper
Edward Loper

Reputation: 15944

Try using "/bin/echo" rather than echo (which is your shell's echo), and see if that helps?

Upvotes: 0

ghoti
ghoti

Reputation: 46876

Works for me.

ghoti@pc $ cat echotest
#!/usr/local/bin/bash

start() {
    # Sample code to make sure that code within the if .. fi is executed
    if [ 1 -eq 1 ]; then
        echo "Start server"
        /usr/local/bin/python echotest.py
    fi
}

start

ghoti@pc $ cat echotest.py 

print "Test only"

ghoti@pc $ ./echotest
Start server
Test only
ghoti@pc $ 

Is there perhaps a problem with your line endings? Are you editing these files natively in the OS that runs bash, or copying them from a Windows box?

That said, I recommend you structure your start script a little differently. Assuming your python script is launching something in the background, you could do something like this:

#!/bin/bash

start() {
  # Sample code to make sure that code within the if .. fi is executed
  echo -n "mydaemon "
  if /usr/local/bin/python mydaemon.py; then
    echo "started"
  else
    echo "FAILED to start"
  fi
}

start

If the python script it itself a daemon that needs to be backgrounded, you can't easily test for its success. And you wouldn't start it this way.

Upvotes: 2

kikuchiyo
kikuchiyo

Reputation: 3421

To capture command output, use back ticks. eg:

captured_output=`/usr/bin/python test.py`
echo $captured_output

Upvotes: 1

Related Questions