1

I want to capture inotify CLOSE_WRITE events in a directory and write CSV info to a history file.

My attempt :

#!/bin/bash
dir=/home/stephen/temp
host=$(hostname)
inotifywait -e close_write -m --timefmt '%Y-%m-%d,%H:%M' --format '%T,$host,%e,%w,%f' $dir | while read event;
do
    echo $event
done

This produces

2022-06-14,16:58, `hostname`, CLOSE_WRITE,CLOSE, /home/stephen/temp/, testfile.txt

I've tried $host and $(hostname) with the same effect. The event's format definition does not accept externally defined variables.

I could wrap it all up in a python script but I'd rather find a shell native solution.

Stephen Boston
  • 2,178
  • 4
  • 32
  • 55

1 Answers1

1

You can insert any string (even multi-line) stored in a variable or use command substitution as long as you keep in mind the rules that apply to expansion when quoting. Anything inside single quotes will be printed literally. Break single quotes and use double-quotes for variables or command substitution that you want expanded. See
What is the difference between the "...", '...', $'...', and $"..." quotes in the shell?

e.g. in your particular case using a format like

--format '%T, $host: '"${host}"',%e,%w,%f'

or

--format '%T, $host: '"$(hostnamectl hostname)"',%e,%w,%f'

prints

2022-12-20,06:21, $host: tuxedo,CLOSE_WRITE,CLOSE,./,test

so the first $host is printed literally while the part between double-quotes is expanded to the host name.

don_crissti
  • 82,805