我正在尝试编写脚本来检测文件何时添加到特定的文件夹,并使用最后一个文件添加名称运行命令。 我特别想做的是为每个文件添加一个特定的文件夹中创build一个QR码。
所以我需要做的是:当一个文件被添加到文件夹时检测,抓住基本文件名并传递给qrencode -o filename.png mysite / filename.ext
理想情况下,它有一个开机启动的cronjob。
我正在读关于使用inotify的一些东西,但我不知道如何做到这一点。
非常感谢!
您可以使用inotifywait来达到所需的结果。
示例 –
While true <br> Do <br> inotifywait -r -e create /directory && /bin/bash "Your-script" <br> Done
用nohup在后台运行这个脚本
尝试incron。 它在大多数分销商都可以通过同名软件包获得。 我将使用Debian和CentOS作为例子,只要它涵盖几乎所有的情况。
步骤是这样的:
1)安装incron
# For Debian apt-get install incron # For CentOS yum install incron
在CentOS中,您还需要手动启动并启用它。
# For CentOS6 chkconfig incrond on service incrond start # For CentOS7 systemctl enable incrond.service systemctl start incrond.service
2)将你的用户添加到文件/etc/incron.allow (只是添加用户名)
3)用命令incrontab -e添加incrontab规则
规则会是这样的:
/full/path/to/your/directory/ IN_CREATE your_script $#
IN_CREATE是在监视目录中创build文件或目录的事件。
your_script是您的脚本的名称,需要该文件并完成所有工作。
$#是文件的名称,触发事件。
在你的情况下,你需要改变文件的扩展名,所以最好是创build一个简单的脚本,它接受文件并执行所有的操作。
类似的东西(我试图检查一切,但它仍然可以包含错误 – 使用前手动检查 ):
#!/bin/bash # Setting constants output_extension='.png' path_to_save_files='/full/path/to/needed/folder/' # Using quotes and $@ to catch files with whitespaces input_file="$@" # Verifying input extension [[ "$input_file" =~ ".*\.txt" ]] || exit # Cutting everything from the start to last '/' appeared input_name=${input_file##/*/} # Cutting everything from the end to first '.' appeared short_name="${input_name%.*}" # Creating full name for output file output_name="${short_name}${output_extension}" # Creating full path for your output file output_file="${path_to_save_files}${output_name}" # Performing your command at last qrencode -o "$output_file" "$input_file"