Debian – Bash script as daemon on debian

daemondebianinotify

i have a short script in bash, which need to run as daemon on background. It's based on inotifywait, which should wait for changes on specified folder and in case of any changes it should runs copy process.

#! /bin/sh    
case "$1" in
  start)
                dir=/var/www/www/source/
                target=/var/www/www/htdocs/application/cache/target/

                inotifywait -m "$dir" --format '%w%f' -e close_write |
                    while read file; do
                        cp  "$file" "$target"
                    done        
        ;;
  stop)

        ;;
esac

i already placed it to /etc/init.d, after save run update-rc.d myscript defaults, but now, when i try start it throw service start command it stop stucked on messages from inotifywait.

/etc/init.d/bash start
Setting up watches.
Watches established.

Can you please give me some hint how to run it in background process withouth any output messages (in ideal way immediately after startup)?

Best Answer

So I got this to work, but its a pretty ugly hack. For how to properly write init scripts I suggest this link.

What I wanted to do was just put the process in the background with "&".

/etc/init.d/myinitscript.sh

    #! /bin/sh
    case "$1" in
      start)
        dir=/var/www/www/source/
        target=/var/www/www/htdocs/application/cache/target/

        inotifywait -m "$dir" --format '%w%f' -e close_write |
          while read file; do
            cp  "$file" "$target"
          done & ## <--- why not just put it in the background?
      ;;

      stop)
      ;;
    esac

This "works"... for certain values of "work". "myinitscript.sh" runs on start, and does what it is supposed to do, but results in this hung process:

$ ps aux | grep -i init
[... snip ...]
root      2341  0.0  0.1   4096   600 ?        Ss   18:02   0:00 startpar -f -- myinitscript.sh
[... snip ...]

The cause of and possible solutions to this problem can be found here.

My subsequent solution is ugly, and if you're doing this in production, then you're doing it wrong.

I'm using two scripts, one in /etc/init.d and another in /root.

/etc/init.d/myinitscript.sh

    #! /bin/sh
    case "$1" in
      start)
        /root/initscriptbody.sh > /dev/null 2>&1
      ;;

      stop)
      ;;
    esac

Not re-directing stdout and stderr to /dev/null results in the hung 'starpar' process. The second script contains all the functionality and it is here it can be put in the background without resulting in the hung 'starpar' process:

/root/initscriptbody.sh

    #! /bin/sh
    dir=/var/www/www/source/
    target=/var/www/www/htdocs/application/cache/target/

    inotifywait -m "$dir" --format '%w%f' -e close_write |
    while read file
    do
        cp  "$file" "$target"
    done & ## <-- no problem backgrounding this now