Evgeny Pokhilko's Weblog

Programmer's den

Run a bash script with sudo, nohup and in the background

This command will run script.sh under super user and you can disconnect and come back later:

sudo nohup bash script.sh &

It’s useful if you don’t have Screen or you want the process to close when it finishes without a screen session hanging around.

By default, the output will go to nohup.out. You can change it by redirecting it to a file:

sudo nohup bash script.sh > script.out &

nohup runs a command immune to hangups. It redirects input and output of the process. If you want to connect to the server again and see the output, use tail, as below:

tail -f script.out

The command will  be printing output as your command produces it as if it runs in your terminal session. Ctrl-C will terminate tail but not the nohup command.

If you need to kill the command before it finishes, find the process id first with:

sudo ps -Af | grep “bash script.sh”
sudo kill <process id>

I hope it helps.

February 20, 2012 Posted by | Linux, Networking | | 3 Comments