在文件夹打开或内容更改时运行bash脚本

时间:2011-12-18 18:52:50

标签: bash

如果我有一个存储在文件夹中的bash脚本,是否可以在文件夹打开时运行它?

第一个例子

假设我在共享文件夹中有脚本s(例如在Dropboxfoo,并且只要用户输入

cd /path/to/foo

我想显示一条消息,让我们说Hello, visitor!。我怎么能这样做(如果可以的话)?

我已经看过this问题,但我没有找到答案中说的内容的例子。


如果以一种简单的方式无法实现,是否可以在检测文件夹内容更改时运行相同的脚本,还是需要第二个脚本来检查然后运行前者?

第二个例子

相同的脚本s位于同一共享 foo文件夹中。如果我做了像

这样的事情
touch test.txt

foo文件夹中,我希望显示另一条消息,假设You have created a new file!或相应地将文件重命名为该文件夹的标准。


使用此配置,我必须确保进入该文件夹的任何人触发脚本,但我无法重新定义任何内置函数,也无法修改bash文件。

2 个答案:

答案 0 :(得分:4)

另一种方法是,将这样的东西添加到.bashrc:

export CURPROMPTWD="$PWD"
export PROMPT_COMMAND=detect_dir_change

function detect_dir_change()
{
    local newcwd=$(realpath "$PWD")
    if [[ "$CURPROMPTWD" != "$newcwd" ]]
    then
        CURPROMPTWD="$newcwd"

        #### EDITED FOR COMMENT ####
        if [[ "$newcmd" == "/some/specific/path" ]]; then
            ./run_welcome.sh
        fi
    fi
}

请注意,我使用的realpath可能在您的系统上不可用。它旨在避免将更改的目录从“〜”更改为“/ home / user”到“../user”等。

该示例使用简单检测来检测用户何时更改为Git工作树根并使用Gi​​t本身显示该树的状态。

检测变化:

您可以使用find调整它。我建议使用一些限制器(下面显示的-maxdepth和-mmin)来防止这种限制因素成为资源消耗。我确信在使用inotify时会有更多高性能选项(但我不确定它们是否可以从bash轻松访问)。

export CURPROMPTWD="$PWD"
export PROMPT_COMMAND=detect_dir_change
export CURPROMPTCHANGEID=""

function detect_dir_change()
{
    local newcwd=$(realpath "$PWD")
    if [[ "$CURPROMPTWD" != "$newcwd" ]]
    then
        CURPROMPTWD="$newcwd"
        if [ -d .git/ ]; then
            echo "Welcome into you git working tree at $newcwd"
            git status
        fi
    fi

    # due to 
    # * -maxdepth 3, changes lower than 3 levels deep below the working
    #   directory won't be seen
    # * -mmin -10, changes made longer than 10 minutes ago won't be seen; this
    #   also implies that being idle in a workdir for over 10 minutes will be
    #   detected as a 'modified working directory' (for the simple reason that
    #   is has no changeid in that case and it will compare as _unequal_ to the
    #   last-seen changeid)
    #
    # Feel free to drop both -maxdepth or -mmin if that's not
    # appropriate/necessary for your use case
    #
    # Consider adding '-type f' to only take modifications to files into
    # account. 
    # --> However, in that case, you'd probably want to watch -cmin _as well
    #     as_ -mmin (since new files won't be seens as recently modified :))
    local changeid=$(find -maxdepth 3 -mmin -10 -printf '%T+\t%i\0' | sort -z | xargs -0 -n1 | tail -1)
    if [[ "$CURPROMPTCHANGEID" != "$changeid" ]]
    then
        CURPROMPTCHANGEID="$changeid"
        echo Run some update due to recent changes
    fi
}

答案 1 :(得分:1)

这可能不是一个好主意,但是,你可以做你所描述的。对于用户的.bashrc,您可以添加以下内容:

function cd ()
  { builtin cd "$@" ; if [[ $PWD = /path/to/foo ]] ; then ./s ; fi ; }

(不用说,这里有很多警告和限制。你正在修改一个基本的Bash行为,这通常不是一个好主意。)