【问题标题】:Run "N" Shell Scripts in Folder在文件夹中运行“N”个 Shell 脚本
【发布时间】:2019-04-03 06:08:02
【问题描述】:

我有一段工作代码可以运行目录中的所有脚本: Run all shell scripts in folder

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 个文件的运行顺序对我来说并不重要。

【问题讨论】:

  • 但是为什么呢?你到底想达到什么目的?为什么不只列出要运行的三个文件?这个问题的背景是什么?
  • 因为文件的顺序并不重要,而且我不想手动重新键入每组文件。例如,我想让它每 24 小时运行 30 个文件。
  • .sh 脚本在完成运行后会自行删除,所以如果我说执行脚本 {1..3},它们将在之后被删除。
  • @Bernhard 运行的文件是任意的,我只是不想一次提交。

标签: linux bash shell loops automation


【解决方案1】:

find 脚本,获取head,然后使用xargs 执行。

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

您可以使用简单的-P0 选项与xargs 并行运行脚本。您可以使用一些xargs sh -c 'bash "$@" -H || exit 125' -- 编写xargs 的脚本,以使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

或在子shell本身中等待孩子:

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

【讨论】:

  • 嗨,Kamil,这最终奏效了,还有一件事……是否可以在 xargs 语句中添加 sleep 5 命令?我最终使用了“find . -name '*.sh' | head -n 10 | xargs -n1 sh”
  • 在提交脚本中添加睡眠而不是 xargs 看起来更容易!
  • 当然,你可以做任何事情,但引用 get 习惯了。你在 xargs 中运行一个命令并将参数传递给它,你就可以运行 shell。所以xargs -n1 sh -c 'sh "$@" ; sleep 1' -- 将按预期工作。 "$@" 在 xargs 内的 sh 内扩展为参数。将-t 添加到xargs 以观察并将-x 添加到sh 以进行调试,例如。 xargs -t -n1 sh -x -c ' sh "$@" ; sleep 1' --
  • 非常感谢
【解决方案2】:

来自 cmets,记录进程运行次数

count=0
for f in *.sh; do
    bash "$f" -H || break
    ((++count>=3)) && break
done

【讨论】:

  • 现在试试这个
  • 逐字尝试,它仍在运行文件夹中的所有文件。不知道为什么?
  • 是否有另一个循环,否则没有原因,您可以添加echo "$count process launched"跟踪
  • 没有其他循环,我要手动输入shell看看。
  • 什么是告诉计数器计数?
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 2014-06-11
  • 2017-03-08
相关资源
最近更新 更多