Search code examples
bashinotifyinotifywait

run inotifywait on background


I have this code copied from linuxaria.com as example and work just fine on my case the problem is when I exit from terminal inotifywait stop. I want run on back ground even after exit the terminal. how I can do that?

#!/bin/sh

# CONFIGURATION
DIR="/tmp"
EVENTS="create"
FIFO="/tmp/inotify2.fifo"


on_event() {
  local date=$1
  local time=$2
  local file=$3

  sleep 5

  echo "$date $time Fichier créé: $file"
}

# MAIN
if [ ! -e "$FIFO" ]
then
  mkfifo "$FIFO"
fi

inotifywait -m -e "$EVENTS" --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %f' "$DIR" >       "$FIFO" &
INOTIFY_PID=$!


while read date time file
do
  on_event $date $time $file &
done < "$FIFO"

Solution

  • You can run the script with screen or nohup but I'm not sure how that would help since the script does not appear to log its output to any file.

    nohup bash script.sh </dev/null >/dev/null 2>&1 &
    

    Or

    screen -dm bash script.sh </dev/null >/dev/null 2>&1 &
    

    Disown could also apply:

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

    You should just test which one would not allow the command to suspend or hang up when the terminal exits.

    If you want to log the output to a file, you can try these versions:

    nohup bash script.sh </dev/null >/path/to/logfile 2>&1 &
    screen -dm bash script.sh </dev/null >/path/to/logfile 2>&1 &
    bash script.sh </dev/null >/path/to/logfile 2>&1 & disown