首页 > 解决方案 > 在文件夹中运行“N”个 Shell 脚本

问题描述

我有一段工作代码来运行目录中的所有脚本: 在文件夹中运行所有 shell 脚本

for f in *.sh; do \
bash "$f" -H || break
done

我还有运行一系列 .sh 脚本的代码:

for f in {1..3}madeupname.sh; do \
bash "$f" -H || break
done

现在,我不想运行所有 .sh 脚本或一系列 .sh 脚本,而是想运行“N”个 .sh 脚本,其中 N 是任意数字,例如 3 个 .sh 脚本。

N 个文件的运行顺序对我来说并不重要。

标签: linuxbashshellloopsautomation

解决方案


find脚本,获取head,然后使用xargs.

find . -name '*.sh' | head -n 10 | xargs -n1 sh

xargs您可以使用简单的-P0选项并行运行脚本。您可以xargs使用一些脚本xargs sh -c 'bash "$@" -H || exit 125' --xargs以非零状态退出,或者在任何脚本运行失败或其他情况后立即退出。

如果您对 不熟悉xargs,只需做一个简单的while read循环:

find . -name '*.sh' | head -n 10 | 
while IFS= read -r script; do
    bash "$script" -H || break
done

同时,您必须摆脱管道子外壳:

while IFS= read -r script; do
    bash "$script" -H || break &
done < <(
     find . -name '*.sh' | head -n 10
)
wait # for all the childs

或等待子外壳本身的孩子:

find . -name '*.sh' | head -n 10 |
{
    while IFS= read -r script; do
        bash "$script" -H || break &
    done
    wait
}

推荐阅读