如何在转到目录时自动运行bash脚本?

时间:2011-04-08 11:21:59

标签: bash

我正在使用rvm和bundler对我的所有项目进行沙盒处理,因此它们都是独立的,所有依赖项都可以保存在源代码管理中。在其中一个中,我使用保存在/ bin文件夹中的bin运行项目。因此,我需要将其添加到PATH变量中。但是,我希望在项目路径中的文件中完成此操作,因此它会自动完成。

这是我的脚本,位于名为“.runme”的文件中:

# .runme
# add local bin folder to PATH unless it's already in there
function __bin_dir {
  echo "`pwd`/bin"
}
function __have_bin {
  echo $PATH | grep "^$(__bin_dir)"
}
[ "$(__have_bin)" == "" ] && export PATH=$(__bin_dir):$PATH

我可以在进入它所在的文件夹时自动运行吗?

3 个答案:

答案 0 :(得分:3)

如果您能够将内容添加到需要此功能的每个用户的.bashrc文件中,您可以挂钩cd操作来检查您需要的内容。

还有另外一个关于如何挂钩cd操作的问题:Is there a hook in Bash to find out when the cwd changes?

我不熟悉RVM,但他们似乎有一些关于挂钩cd的文档:https://rvm.beginrescueend.com/workflow/hooks/

答案 1 :(得分:1)

另一个技巧是将函数放在PS1中,如

export PS1='...\[$(.runme)\]

(用您PS1中已有的任何内容替换...)。这将在每个新提示处运行检查。

但是,您希望尽可能快地运行命令,因为它的运行时会延迟显示提示。一个良好的开端是使它成为一个bash函数并且只使用bash内置函数,因此它不必分叉来运行任何外部程序(如grep)。

答案 2 :(得分:1)

通过一个简单的别名,这是一个不那么具有侵入性的替代方案:

alias lx='PATH="./bin:$PATH"'

然后,您可以在任何具有lx子文件夹的文件夹中使用bin L ocal e X ecution)来执行脚本一条路径;例如,要从当前目录执行脚本./bin/start-server,请运行:

 lx start-server

如果您想根据本地可执行文件启用标签完成,请将以下内容添加到您的bash配置文件中(在OSX和Linux上测试):

# Install the custom tab-completion function defined below.
complete -F _complete_lx -- lx


# Command-completion function for lx: tab-completes the executables in 
# the ./bin subfolder.
_complete_lx() {

    # Set the directory in which to look for local executables.
  local localExeDir='./bin'

      # Get the current command-line token.
  local token=${COMP_WORDS[$COMP_CWORD]}
  local tokenLen=${#token}

  # Find all local executables.
  read -d ' ' -ra localExes < <(find "$localExeDir" -maxdepth 1 -type f -perm -a=x -exec basename -a {} +;)

  # Filter the list of local executables
  # based on the current command-line token.

  # Turn case-insensitive matching temporarily on, if necessary.
  local nocasematchWasOff=0
  shopt nocasematch >/dev/null || nocasematchWasOff=1
  (( nocasematchWasOff )) && shopt -s nocasematch

  COMPREPLY=()
  for localExe in "${localExes[@]}"; do
    if [[ ${localExe:0:$(( tokenLen ))} == "$token" ]]; then
      COMPREPLY+=( "$localExe" )
    fi
  done

  # Restore state of 'nocasematch' option, if necessary.
  (( nocasematchWasOff )) && shopt -u nocasematch

}
相关问题