Bash: Running a background service for the duration of another process

Posted on

Bash: Running a background service for the duration of another process – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about linux, bash, ssh-tunnel, , .

I am running some automated scripts. For some tasks I sometimes need a ephemral background “service” to run. For example, I want to setup an ssh tunnel, run a test, and then have the tunnel removed.

ATM I am using some lengthy code:

#!/usr/bin/env bash
function automated_task(){
    ssh -A -D 9999 some_server "sleep $socksProxyTimeout; " &
    sleep 3

    function cleanUp(){
        echo shutting down background processes...
        kill -9 $sockProxyPid || true
        cd ../../

    trap 'cleanUp' EXIT

I do not like this solution much, because I think cleanup is only called once the entire script exits, not just “automated_task”. I would really like to have the code as local as possible. What I’d really like to do is somehow specify for a background process to run only as long as the foreground process is still running.

Solution :

I would try storing the child process ID as indicated here


   if [ "x$sshPID" != "x" ]; then
       kill "$sshPID"

connect() {
    ssh -A -D 9999 some_server "sleep $socksProxyTimeout; " & sshPID=$!
    trap 'disconnect' EXIT

sleep 3

You may be able to use ssh -O exit some_server instead of kill, depending on if you use ControlMaster setup. (see ssh docs).

Leave a Reply

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