3

I want to run a shell script over the weekend, but I wanna make sure if the terminal loses the connection, my script won't be terminated. I use nohup for the whole script invokation, but I also want to execute some portion of my shell script in a way that if someone closes my terminal, my script runs on the background still. Here is a simple example :

#!/bin/bash

echo "Start the trap" 
trap " " HUP 
echo "Sleeping for 60 Seconds"
sleep 60 echo "I just woke up!"

Please suggest what I should do ? The trap " " HUP seems like not working when I close my terminal tab.

Zoredache
  • 128,755
  • 40
  • 271
  • 413
Alex
  • 31
  • 1
  • 3

2 Answers2

3

Have you considered using screen instead of the nohup approach?

Open a screen session and execute the script as normal. Detach from the session using Ctrl-a Ctrl-d.

When you return, you can reattach to the session using screen -r or possibly, screen -ls and selecting the right session to restore.

Also see: How to reconnect to a disconnected ssh session

ewwhite
  • 194,921
  • 91
  • 434
  • 799
  • There are some scripts you do not want to fail half way through, but you don't want to have to start screen for each time. – Zoredache Nov 13 '12 at 16:25
  • You can use `screen` and `nohup` together. Screen to protect your session and nohup to execute the scripts. – ewwhite Nov 13 '12 at 16:29
  • And if you are writing a script to be used by other people who can't be trusted to remember to start screen first? Some scripts once they start operating really should fully complete. For example a script that resets and updates the rules in an iptables firewall. Or a script that sets up a complex routing table. – Zoredache Nov 13 '12 at 16:38
1

Pretty sure you want trap "" HUP. not trap " " HUP.

trap [-lp] [[arg] signal_spec ...]

ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC. If ARG is absent (and a single SIGNAL_SPEC is supplied) or `-', each specified signal is reset to its original value. If ARG is the null string each SIGNAL_SPEC is ignored by the shell and by the commands it invokes.

The " " is not a null string, but "" is.

Zoredache
  • 128,755
  • 40
  • 271
  • 413
  • I don't see the value of `trap '' EXIT`, since `EXIT` isn't a real signal; it's just synthesized by bash at script end. So you're just telling bash to do nothing additional when the script ends. That doesn't sound useful. – tylerl Nov 13 '12 at 16:51
  • @tylerl, you are right. – Zoredache Nov 13 '12 at 18:30