在亚历克斯回答我的步骤之后:
创建外壳代码
root@ip[/]# touch mylog.sh
root@ip[/]# nano mylog.sh复制mylog.sh中的代码
#!/bin/bash
echo "File $1 created." >> /mylog.log权限
root@ip[/]# chmod +x mylog.sh创建日志文件
root@ip[/]# touch mylog.log 开冰台
incrontab -e输入新命令
/test/ IN_CREATE mylog.sh $@$#重新加载incron -创建一个新文件-检查日志文件
root@ip[/]# incrontab --reload
requesting table reload for user 'root'...
request done
root@ip[/]# cd test
root@ip[/test]# touch newfile.txt
root@ip[/test]# cd /
root@ip[/]# nano mylog.log但仍然是空日志文件..。我漏掉了什么吗?
最后,使用full path调用shell脚本完成了这样的任务:
/test/ IN_CREATE /mylog.sh $@$#发布于 2016-02-03 10:51:28
您通常可以在/var/log/messages中找到incron日志。
如果要将事件记录到特定文件,可以使用:
/test/ IN_CREATE mylog.sh $@$#其中mylog.sh是一个shell脚本,它处理日志记录。
#!/bin/bash
echo "File $1 created." >> /home/myuser/filescreated.log不要忘记通过chmod +x mylog.sh对这个shell脚本授予执行权限。
说明:一旦开始为正在调用的命令使用参数,就必须将其全部放入shell脚本中。因为incron不将参数传递给您的命令,而是将其解释为自己的参数。
不要忘记调用incrontab -在更改incrontab后重新加载。
另一个例子
incrontab -e
/text/ IN_CREATE /home/myuser/mylog.sh $@ $#mylog.sh
#!/bin/bash
echo "$(date) File $2 in $1 created." >> /home/myuser/log.txt发布于 2022-11-06 22:31:12
按照Alexander的Baltasar answer,您还可以拥有一个执行重定向的脚本,并使您的结束脚本不受这种逻辑的影响。
低于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$ chmod 770 std_wrapper.sh):在您的incrontab ($ incrontab -e)中:
/test/ IN_CREATE /path/std_wrapper.sh /path/log/test.create /path/actual_script.sh $# $@ $%actual_script.sh看起来可能是这样的:
#!/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 -->"连续创建两个文件(不到10秒)
$ touch /test/new-file && sleep 5 && touch /test/another-file会创建这样的日志:
$ 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 -->https://stackoverflow.com/questions/35019277
复制相似问题