BlinkyTop
BlinkyTop

Reputation: 1144

Run a Bash Command on File Change?

My question is how can I run a Bash command on some file change?

For example, if I am writing a C program and every time the file is saved I run the command rm output; gcc program.c -o output; ./output automatically

Upvotes: 0

Views: 527

Answers (2)

etr
etr

Reputation: 1247

You can use inotifywait for this specific purpose.

while true; do
  change=$(inotifywait -e close_write,moved_to,create .)
  change=${change#./ * }
  if [ "$change" = "program.c" ]; then rm output; gcc program.c -o output; ./output; fi
done

Upvotes: 1

Vaughn Cato
Vaughn Cato

Reputation: 64308

You could use make and watch:

Makefile:

output: program.c
        gcc program.c -o output
        ./output

then

$ watch make

in a separate terminal.

However, there will be a small delay between when you save program.c and when it gets run.

Upvotes: 3

Related Questions