Search code examples
stdoutraspbianstderrio-redirection

Redirection of stdout and stderr to file not working on raspbian


I am trying to redirect STDOUT and STDERR to a log file on raspberry pi. My .sh script contains this line

sudo ./main.py &> client.log &

The script runs correctly as it transfers data to and from my server, but client.log file remains empty. I tried &>; &>>; >> with 2>&1; and |&. None of them write any data to client.log.

sudo ./main.py

produces both stdout and stderr output. What am I doing wrong?


Solution

  • The syntax you are looking for is:

    sudo ./main.py > client.log 2>&1 &
    
    • > client.log redirects standard output to the file client.log
    • 2>&1 redirects stderr to stdout
    • & at the end of the line runs this in the background so you can continue working at the command prompt.

    Note: if you log off while the background command is running, it will be killed. You can override this behavior by adding nohup to the beginning of the line. For more information google bash jobs


    Edited to add additional information after comment below

    revised syntax:

    sudo stdbuf -o L -e L ./main.py > client.log 2>&1 &
    
    • stdbuf modifies the default linux output buffering
    • -o L Flushes stdout at the end of every line
    • -e L Flushes stderr at the end of every line