10

We have a long running process on a remote server which is kicked off manually from time to time. Unfortunately internet connections die, kernels panic and a whole host of other challenges can be encountered by the ssh session used to connect and start the job.

Screen seems like a perfect way to ensure the process isn't interrupted. However, relying on a person to always remember to start screen and then run the script to start the process is a problem waiting to happen. Is there a way from the script I can check to see if the script is being called from within screen? If it is the process will continue otherwise the script will exit with a message instructing the user to run screen first.

cclark
  • 567
  • 2
  • 6
  • 14
  • Possible duplicate of [How do I know I'm running inside a linux "screen" or not?](https://serverfault.com/questions/377221/how-do-i-know-im-running-inside-a-linux-screen-or-not) – Andrew Schulman Feb 14 '18 at 21:47

2 Answers2

11

There is an environment variable for that. If it is being run within screen, $TERM will be screen. It's that simple; just do an if on it. For instance,

if [ $TERM != 'screen' ]; then echo foo; else echo bar; fi

will echo bar when in screen; foo otherwise.

Falcon Momot
  • 24,975
  • 13
  • 61
  • 92
7

While you're working with screen, why not run the script with 'nohup'? This will also ensure that it continues to run if you get disconnected.

It outputs to a file by default, so you can use other tools to monitor script output if you wish.

Magellan
  • 4,431
  • 3
  • 29
  • 53
  • 1
    While running with nohup would achieve the same outcome of ensuring the process continues to run would I not still have the same issue of someone potentially forgetting to run the script with nohup? Or is there a way in a script to ensure 'nohup' was used or do I need to create a wrapper script which calls my original script with nohup? – cclark Oct 03 '12 at 06:04
  • Yeah. While I love my padawans (junior sysadmins) like I love my kids, they frequently forget those kinds of things. So everything gets wrapped up so that they don't have to remember what things to type in to prefix the important commands. – Magellan Oct 03 '12 at 06:13