Bash 仅在特定目录中访问子文件夹中的脚本

Bash Getting Access To Scripts In Subfolders Only While In Certain Directory

详细说明,

项目结构

current-working-directory
  -- scripts [d]
    -- script1 [d]
      -- script1 [f]
    -- script2 [d]
      -- script2 [f]
  -- README [f]
  -- executable [f]

主要思想:我希望能够运行说function1位于script1 只要 我在 当前工作目录 或任何子文件夹中。

我在这方面进行了多次尝试:

IDEA#1 .bashrc

function cd {
    builtin cd $@
    local dir
    if [ -d "bpm_modules" ]; then
      for dir in $(ls bpm_modules);do
        . "$PWD/bpm_modules/$dir/$dir"
      done
    fi
  }

cd 命令的包装器

警告:因为我获取了文件,一旦我离开目录我仍然可以访问。


IDEA#2 .bashrc

function require {
    # You Have Gone Too Far
    [ "" == "$HOME" ] && return 1
    
    # Assign Parameters Accordingly
    [ $# -eq 1 ] && local CWD="$PWD" && local QUERY=""
    [ $# -eq 2 ] && local CWD="" && local QUERY=""
    local FOUND_MODULE=1

    # Error Handling
    function trapper {
        local BOO=
        local QUERY=
        NOT_FOUND="$(tput setaf 1)[DEPENDENCY]: $(tput sgr0)missing '$QUERY'"
        
        [[ $BOO -eq 1 ]] && echo "$NOT_FOUND"
    }
    
    # If In BCS Initialized Project
    if [ -d "$CWD/.bpm" ]; then
        
        # Check For Module
        for DIR in $( ls $CWD/bpm_modules); do
            [ "$DIR" == "$QUERY" ] && FOUND_MODULE=0 && source $CWD/bpm_modules/$DIR/$DIR
        done
        trap "trapper $FOUND_MODULE $QUERY" $?
    # Else Go Up A Directory Recursively
    else
        CWD_UP1=$(cd $CWD && cd .. && pwd)
        require $CWD_UP1 $QUERY
    fi

}

require 将用于上面项目目录图中的 executable,后跟 script/folder 名称,如 require script1,获取文件并允许我在 executable

中使用函数

Repo @ Github

Package-Library

PS:我有 2 周的 bash 经验,所以...,我很感激任何建议或严酷的事实。

PS1: 'bash puns amirite',这用于bash-package-经理 我目前正在工作。

假设我是 运行 一个名为 my_script.sh 的脚本。如果我想实现你的 require 函数,如果这个脚本位于目录 $my_dir 中,那么它将获取参数中给出的脚本,否则会崩溃,你可以这样做:

#!/bin/sh

require() {
    if realpath --relative-to="$my_dir" "" | fgrep ../; then
        echo Script "" is not located in directory "$my_dir", exiting. >&2
        exit 1
    fi
    source 
}

请注意,如果 realpath 返回的路径中的目录以 .. 结尾,这将失败。我认为这是一个合理的限制,但要知道,为了解决这个问题,您可以将 fgrep ../ 替换为 grep '\(^\.\./\)\|/\.\./'