【问题标题】:Bash script to read a file and run a command based on a specific string [closed]用于读取文件并根据特定字符串运行命令的 Bash 脚本 [关闭]
【发布时间】:2014-10-15 07:00:40
【问题描述】:

我需要一个 bash 脚本,当文件保存到特定目录(文件名可以是任何内容)时,读取其内容,然后,如果在文件中找到特定字符串,则运行特定命令/或另一个脚本。

我查看了Bash script: perform actions based on file contents,但这个脚本似乎依赖于被命名的文件。我的 bash 脚本几乎没用,所以希望有人能提供帮助:)

【问题讨论】:

  • 尝试写一些东西,然后我们可以给你反馈。

标签: linux bash


【解决方案1】:

如果你安装了inotify-tools 包,你可以使用inotifywait

#!/bin/bash

DIR_TO_WATCH=/tmp
STRING=foobar

cd "$DIR_TO_WATCH"

inotifywait -qme close_write --format '%f' -r ./ | while read changed_file; do
  if grep "$STRING" "$changed_file" &>/dev/null; then
    echo "$STRING found on file $changed_file!"
  fi
done

我建议您查看inotifywaits manual 以了解有关命令行选项的更多详细信息

【讨论】:

  • 这太棒了。我正在对其进行一些修改以包含几个匹配项,运行一个脚本。
猜你喜欢
  • 1970-01-01
  • 2014-11-07
  • 2017-01-08
  • 2012-07-13
  • 2018-04-27
  • 1970-01-01
  • 2020-10-13
  • 2015-06-19
  • 2011-01-22
相关资源
最近更新 更多