Tomas Gonzalez
Tomas Gonzalez

Reputation: 1175

Linux Bash - redirect errors to file

My objective is to run a command in the background and only create a log if something goes wrong.

Can someone tell me if this command is OK for that?

bash: ./command > app/tmp/logs/model/123.log 2>&1 & echo $! >> /dev/null &

The command itself is unimportant (just a random PHP script).

And / or explain how to route the results of my command to a file only if it is an errorand?

Also, I cant understand what "echo $!" does (I've copied this from elsewhere)...

Thanks in advance!

Upvotes: 2

Views: 79

Answers (1)

John1024
John1024

Reputation: 113834

If I understand correctly, your goal is to run command in the background and to leave a log file only if an error occurred. In that case:

{ ./command >123.log 2>&1 && rm -f 123.log; } &

How it works:

  • {...} &

    This runs whatever is in braces in the background. The braces are not strictly needed here for this exact command but including them causes no harm and might save you from an unexpected problem later.

  • ./command >123.log 2>&1

    This runs command and saves all output to 123.log.

  • &&

    This runs the command that follows only if command succeeded (in other words, if commmand set its exit code to zero).

  • rm -f 123.log

    This removes the log file. Since this command follows the &&, it is only run if command succeeded.

Discussion

You asked about:

echo $! >> /dev/null

echo $! displays the process ID of the previous command that was run in the background. In this case that would be ./command. This display, however, is sent to /dev/null which is, effectively, a trash can.

Upvotes: 4

Related Questions