IT How Tos

Home

About

Sitemap

Contact

How to Create a Linux Screen to Run a Command and be Able to Stop Later

  • To start a command within a screen session, run the following command:
screen -dS ${title} -m  ${command}
  • To stop the screen session that was started above than run the following command:
screen -X -S ${title} quit
  • To build the script to do so:
    • Under /usr/local/bin/
      • create a file called backgcomm (or something different)
  • Script:
#!/bin/bash

function usage {
    echo "Usage `echo $basename $0` <-v|--verbose> new  <command>"
    echo  "...or `echo $basename $0` <-v|--verbose> stop <title>"
}

function startscreen {
    screen -dS ${title} -m ${comm}
}

function stopscreen {
    screen -X -S ${title} quit
}

if [ -z "$1" ]; then usage; 
elif [ "new" = "$1" ]; then
    title=$2
    comm=$3
    startscreen
elif [ "stop" = "$1" ];then
    title=$2
    stopscreen $2
elif [ "-v" = "$1" ] || [ "--verbose" = "$1" ]; then
    if [ "new" = "$2" ]; then
        title=$3
        comm=$4
        echo "creating new screen ${title} with command - ${comm}"
        startscreen
    elif [ "stop" = "$2" ]; then
        title=$3
        echo "stopping screen ${title}"
        stopscreen
    else
        usage
    fi
else
    usage
fi

</code></pre>
<!-- Version - 1.0.0 - rc -->
</td>
</tr>
</table>
</center>
<!-- beep -->
</body>