Run a shell script in the background on Linux

Typically, I will need to run a shell script on a Linux server which I know will take a while to execute. I will sometimes also need to check up on the output of the script as it runs.

Whenever I run a script which may run for over 10 seconds, I need to ensure that a drop-off in SSH connection will not terminate script execution (especially important when working on the move, e.g. on a train).

By using the screen package on Linux (it must be installed prior to use), I can run the command on a different window. This package allows us to resume terminated SSH sessions.

Commands

screen

php ./long-running-script.php > ~/output-long-running-script.txt

tail -n 100 -f ~/output-long-running-script.txt

Explanation

screen is used to begin a new screen window/session. The screen window can be detached and resumed.

The script in this case will have its output redirected (written to) to the file at the location provided (~/output-long-running-script.txt).

The tail command combined with the -f flag will watch the end of the file, to which we are redirecting our script’s output, allowing us to see the contents of the file as it is updated by our script.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *