Following with Alexander's Baltasar answer, you could also have a script that does the redirection, and keep your end scripts free of that logic.
Below std_wrapper.sh
:
#!/bin/bash
### FLAGS
set -Eeuo pipefail
### INIT SCRIPT
SCRIPT_FULLNAME=$(basename -- ${0})
usage="usage: ${SCRIPT_FULLNAME} log_file target_script target_file watched_dir event"
## ARGUMENTS
log_file="${1}"
target_script="${2}"
target_file="${3}"
watched_dir="${4}"
event="${5}"
### MAIN
if [ -z "${log_file}" ] || [ -z "${target_script}" ] || [ -z "${target_file}" ]; then
echo "${usage}" >&2
exit 1
fi
# do the actual call and apply the redirection:
${target_script} "${target_file}" "${watched_dir}" "${event}" >> "${log_file}" 2>&1
- make sure the script can be run (
$ chmod 770 std_wrapper.sh
):
In your incrontab
($ incrontab -e
):
/test/ IN_CREATE /path/std_wrapper.sh /path/log/test.create /path/actual_script.sh $# $@ $%
actual_script.sh
could look something like this:
#!/bin/bash
### FLAGS
set -Eeuo pipefail
### Input Parameters
filename="${1}"
watched_dir="${2}"
event="${3}"
full_filename="${watched_dir}${filename}"
### Main
dt="$(date '+%d/%m/%YT%H:%M:%S')"
echo "$dt (event:) $event (file:) $filename (dir:) $watched_dir <----- going to process ----->"
echo "sleeping 10 seconds..."
sleep 10
dt="$(date '+%d/%m/%YT%H:%M:%S')"
echo "$dt (event:) $event (full_filename:) $full_filename <----- returning from sleep -->"
Creating two files consecutively (in less than 10 seconds)
$ touch /test/new-file && sleep 5 && touch /test/another-file
Would create a log like this:
$ cat /path/log/test.create
07/11/2022T08:00:50 (event:) IN_CREATE (file:) new-file (dir:) /test/ <----- going to process ----->
sleeping 10 seconds...
07/11/2022T08:00:55 (event:) IN_CREATE (file:) another-file (dir:) /test/ <----- going to process ----->
sleeping 10 seconds...
07/11/2022T08:01:10 (event:) IN_CREATE (full_filename:) /test/new-file <----- returning from sleep -->
07/11/2022T08:01:15 (event:) IN_CREATE (full_filename:) /test/another-file <----- returning from sleep -->