Trap “” HUP v.s Nohup ? How to run a portion of shell script in nohub mode

command-line-interfacenohupshell-scripting

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.

Best Answer

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