Search code examples
gitbashshellgithooksnohup

How to make "nohup ./script.sh & disown" working in post-receive git hook?


I expect that the script called with

nohup ./script.sh & disown

will be executed in background and it's output won't be seen while pushing. But I see the output and I have to wait a delay. Here are the contents of the called script:

#!/bin/bash
echo 'test'
sleep 5

How to make it run as a detached process from my git hook script?
Thanks

Update

I've understood that I need no nohup... For some reason it prevented running my script in background (and maybe disowning it too). So I've got the following string in my hook, and it's working now:

./script.sh > /dev/null 2>&1 & disown

Thanks to @CharlesDuffy for pointing out uselessness of nohup (in this particular case) to me.


Solution

  • If you want your script to detach itself, consider:

    #!/bin/bash
    
    # ignore HUP signals
    trap '' HUP
    
    # redirect stdin, stdout and stderr to/from /dev/null
    exec >/dev/null 2>&1 <&1
    
    # run remaining content in a detached subshell
    (
      echo 'test'
      sleep 5
    ) & disown
    

    Alternately, you can perform these operations from the parent:

    (trap '' HUP; ./yourscript &) >/dev/null <&1 2>&1 & disown