从 .bash_profile 获取目录中的所有文件

问题描述 投票:0回答:8

我需要允许多个应用程序附加到系统变量(在本例中为 $PYTHONPATH)。我正在考虑指定一个目录,每个应用程序都可以在其中添加模块(例如 .bash_profile_modulename)。在 ~/.bash_profile 中尝试过类似的操作:

find /home/mike/ -name ".bash_profile_*" | while read FILE; do
source "$FILE"
done;

但它似乎不起作用。

bash shell scripting
8个回答
109
投票

不会

 for f in ~/.bash_profile_*; do source $f; done

足够了吗?

编辑:额外的

ls ~/.bash_*
层简化为直接 bash 通配符。


24
投票

Oneliner(仅适用于 bash/zsh):

source <(cat *)

21
投票

我同意上面丹尼斯的观点;您的解决方案应该有效(尽管“完成”后面的分号不是必需的)。但是,您也可以使用 for 循环

for f in /path/to/dir*; do
   . $f
done

ls 的命令替换是不必要的,如德克的回答所示。例如,在

/etc/bash_completion
中使用这种机制来获取
/etc/bash_completion.d

中的其他 bash 完成脚本

3
投票
for file in "$(find . -maxdepth 1 -name '*.sh' -print -quit)"; do source $file; done

到目前为止,这个解决方案是我发现的最容易发布的解决方案:

  • 如果没有文件匹配,不会给出任何错误
  • 适用于多种 shell,包括 bash、zsh
  • 跨平台(Linux、MacOS...)

2
投票

您可以使用此功能来获取目录中的所有文件(如果有):

source_files_in() {
    local dir="$1"

    if [[ -d "$dir" && -r "$dir" && -x "$dir" ]]; then
        for file in "$dir"/*; do
           [[ -f "$file" && -r "$file" ]] && . "$file"
        done
    fi
}

额外的文件检查处理由于目录为空而导致模式不匹配的极端情况(这使得循环变量扩展到模式字符串本身)。


1
投票
str="$(find . -type f -name '*.sh' -print)"
arr=( $str )
for f in "${arr[@]}"; do
   [[ -f $f ]] && . $f --source-only || echo "$f not found"
done 

我测试了这个脚本并且正在使用它。 只需修改

.
之后的
find
以指向包含脚本的文件夹即可。


-2
投票

好吧,我最后做了什么;

eval "$(find perf-tests/ -type f -iname "*.test" | while read af; do echo "source $af"; done)"

这将在当前 shell 中执行源代码并维护所有变量...


-7
投票

我认为你应该能够做到


source ~/.bash_profile_*

© www.soinside.com 2019 - 2024. All rights reserved.