O'Reilly logo

bash Cookbook, 2nd Edition by JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 10. Additional Features for Scripting

Many scripts are written as simple one-off scripts that are only used by their author, consisting of only a few lines—perhaps only a single loop, if that. But some scripts are heavy-duty scripts that will see a lot of use from a variety of users. Such scripts will often need to take advantage of features that allow for better sharing and reuse of code. These advanced scripting techniques can be useful for many kinds of scripts, and are often found in larger systems of scripts such as the /etc/init.d scripts on many Linux systems. You don’t have to be a system administrator to appreciate and use the tips and techniques described here. They will prove themselves on any large scripting effort.

10.1 “Daemon-izing” Your Script

Problem

Sometimes you want a script to run as a daemon, in the background and never ending. To do this properly you need to be able to detach your script from its controlling TTY—that is, from the terminal session used to start the daemon. Simply putting an ampersand on the command isn’t enough. If you start your daemon script on a remote system via an SSH (or similar) session, you’ll notice that when you log out, the SSH session doesn’t end and your window is hung until that script ends (which, being a daemon, it won’t).

Solution

Use the following to invoke your script, run it in the background, and still allow yourself to log out:

nohup mydaemonscript 0<&-1>/dev/null 2>&1 &

or:

nohup mydaemonscript >>/var/log/myadmin.log ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required