在bash脚本中inotify不能使用ldapadd命令

我写了一个bash脚本,用于检测.ldif文件是否已经写入目录,如果写入,则执行ldapadd命令,然后删除该文件。 脚本如下:

 dir="/home/myuser/newldif/" while inotifywait -e create "$dir"; do ldapadd -w "ldappassword" -D "cn=Manager,dc=mydomain,dc=com" -f /home/myuser/newldif/user.ldif rm -rf /home/myuser/newldif/user.ldif done 

这个脚本是这样执行的:

 nohup ./testscript & 

目录newldif最初是空的。 将文件user.ldif复制到此位置时,脚本将执行,但会跳过ldapadd命令并执行rm命令。

另一方面,当我执行没有inotify的脚本(即我完全删除了while循环),它添加了ldap条目,然后删除该文件。

inotify语法有什么问题吗? slapd日志不显示任何错误。 nohup.out文件只显示以下输出:

 Setting up watches. Watches established. Setting up watches. Watches established. Setting up watches. Watches established. 

(每个“设置手表”语句是针对一个被删除的文件)

操作系统是CentOS 6.4,OpenLDAP版本是openldap-2.4.23。

如果rm从这个脚本执行,那么你的逻辑没有任何问题。

这可能是一个计时问题,其中文件在目录中创build,但在脚本运行ldap命令时未填充。 尝试添加一个文件的cat来看看。 然后尝试等待目录上的close_write事件,以便您有一个完全填充的文件。 这可能还不够,因为这取决于你如何写入文件。 通常最安全的方法是在其他地方创build一个临时文件,然后在完全填充时将其移动到位,因为这是更primefaces的文件系统操作。

此外,添加一些错误检查您所期望的或命令的文件也是一个好主意:

 #!/usr/bin/env bash dir="/home/myuser/newldif/" file="user.ldif.tmp" ldf="$dir/$file" while inotifywait -e close_write "$dir"; do # Check if the file we want exists in the directory being monitored. if [ ! -f $ldf ]; then echo "No file [$ldf]"; continue; fi # Add users via ldap echo "Adding users:" mv $ldf $dir/user.ldif ldapadd -w "ldappassword" -D "cn=Manager,dc=mydomain,dc=com" -f $dir/user.ldif || echo "failed adding users" && exit 1 # Remove file when done echo "Removing file" rm $dir/user.ldif || echo "failed removing file" && exit 1 done