Skip to main content
1 of 3
Mario Vitale
  • 1.1k
  • 10
  • 13

You have a few options, all of which preserve your requirement of terminating your foreground session at the end (which you do with kill $WB).

  1. If possible, use tmux (or screen). It's the most obvious solution for your use case: a disconnection on your end will just cause a detachment of the tmux session, thus the commands you issued will not stop; after that, you could even re-attach to that session if you wanted to check its output (instead of tail -f nohup.out). You wouldn't even need the kill $WB trick, as every single command is executed in the foreground, so a simple exit will suffice. Summary: ssh into your VPS -> execute tmux -> type the commands you listed (without the WB=$$; (, the ) & at the end and substituting kill $WB with a simple exit) -> disconnect, detach and re-attach as needed

  2. If you can't or don't want to use tmux, put your commands in a file. The problem here is basically that nohup can't execute grouped commands (the concept of subshell is exclusive to bash, you can't execute one with nohup), so you could put your code e.g. in the /opt/myscript.sh file:

    #!/bin/bash
    
    #You will pass the PID of the foreground shell as its first argument
    WB=$1
    
    sleep 2h;
    echo "Removing PMA and exiting";
    phpdismod mcrypt mbstring;
    apt-get purge phpmyadmin -y;
    service apache2 restart;
    sed -i 's/Include \/etc\/phpmyadmin\/apache.conf/ /g' /etc/apache2  /apache2.conf;
    kill $WB
    

    Then you can execute it with nohup /opt/myscript.sh $$ &

  3. If you can't or don't want to put them in a file, just execute them like this: nohup bash -c " ...your commands here... ; kill $$" &. The $$ here will still be referring to the outer foreground shell, as it is substituted before it is executed as the bash -c argument.

Mario Vitale
  • 1.1k
  • 10
  • 13