Bash Tip: Closing File Descriptors

I recently found that you can close bash file descriptors fairly easily, it goes like this:

Which makes it easy to daemonize things using only bash (lets face it there are times when you JUST don’t need anything more than a simple bash script, you just need it backgrounded/daemonized). Take this example of a daemon that copies any new files created in a directory to another place on the filesystem

One especially nice detail here is that this wont hang while exiting your SSH session after you start it up (a big pet peeve of mine).

7 thoughts on “Bash Tip: Closing File Descriptors

  1. ndronen

    Yeah, this is broken:

    exec 3>&- # close stdin

    exec 2>&- # close stdout

    exec 1>&- # close stderr

    It should be

    exec 0>&- # close stdin

    exec 1>&- # close stdout

    exec 2>&- # close stderr

    Reply
  2. foo

    why not just start up screen and while true;do sh myscript.sh; done ?

    then attach to the screen session if you ever want to close it. Then you don't ever have to worry about the PID getting recycled, and your script accidentally closing the wrong process!

    Reply
    1. apokalyptik Post author

      @foo Granted. But sometimes screen is not necessary or wanted. checking the PIDfile contents versus the running process list is, naturally, a good idea. But the post was about closing the file descriptors, not writing idfiles or killing processes, so the example is just that: an example.

      Reply
  3. Dennis Birkholz

    You posted this quite some time ago but i have a little improvment for you: use $$ in bashto get the current process id, not pgrep. Otherwise, interesting example.

    Greets,
    Dennis

    Reply

Leave a Reply