The Spaghetti Refactory Established 2015

Bash yourself in the background!

There are many occasions for wanting to run bash scripts in the background. The two that jump out at me are startup scripts and scripts to be run while SSH-ed into a remote server. This post deals mainly with the latter, though it should work for both.

First, create a bash script you want to run. I wanted to monitor the memory of a running EC2 server instance to ensure we didn’t have memory leaking from our app, so here’s my bash script:

# log/memory_profiler.sh
while true
do
date 2>&1 | tee -a /srv/application/my_application/log/memory
free -m 2>&1 | tee -a /srv/application/my_application/log/memory
sleep 1
done

This writes the current datetime and the current memory profile to a log file in my app’s directory.

Then, I wanted to run this script from a detached shell session so that when I closed my SSH connection, it would continue running, and also so that I could continue working within the open shell session. To do this, I use a tool called “screen.” Here’s my command:

screen -d -m -S "Memory Profiler" bash log/memory_profiler.sh

Here’s what’s happening: We run the bash script in a detached (-d) shell session, named (-S) “Memory Profiler”. The -m flag ensures a new shell session is created, regardless of where the screen command is called.

Simple enough, right? Then, to view what’s going on with this detached screen session, you just have to reattach the shell session. If you only have one screen running, enter

screen -r

If multiple, you’ll have to specify the named session.

screen -r "Memory Profiler"

Exit as normal using ctrl+c or typing exit.

If you want to get really fancy, you can run this on a schedule - something I've written about previously.

(Lots of good info in the screen docs.)