在新的分离屏幕中运行 bash 脚本中定义的函数

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

我正在写一个问题,但终于想出了一个解决方案。因为它可能对其他人有用(至少对我未来的自己),所以就在这里。

背景

要在多个自动关闭的独立屏幕中并行运行单个命令,效果很好:

timeslots='00_XX 01_XX 02_XX 03_XX 04_XX 05_XX 06_XX'    
for timeslot in $timeslots;
do
    screen -dmS $timeslot bash -c "echo '$timeslot' >> DUMP"; 
done

但是,如果对于每个时隙,我们想要在屏幕上执行的不是一个命令而是多个(占用大量 RAM)命令,一个接着一个怎么办?

我们可以编写一个函数(其中所有内容都按顺序运行),并在 bash 脚本中添加一个参数。

test_function () {

    # Commands to be executed sequentially, one at a time:
    echo $1 >> DUMP;        # technically we'd put heavy things that shouldn't be executed in parallel
    echo $1 $1 >> DUMP;     # these are just dummy MWE commands
    # ETC                   

}

但是,如何创建使用 $timelot 参数运行此函数的独立屏幕?

stackoverflow 上有很多关于运行不同的可执行脚本文件或使用东西的讨论,但这不是我想要做的。这里的想法是避免不必要的文件,将它们全部保存在同一个小 bash 脚本中,简单干净。

bash gnu-screen
1个回答
0
投票

函数定义(在script.sh中)

test_function () {

    # Commands to be executed sequentially, one at a time:
    echo $1 >> DUMP;        # technically we'd put heavy things that shouldn't be executed in parallel
    echo $1 $1 >> DUMP;     # these are just dummy MWE commands
    # ETC                   

}
export -f test_function # < absolutely crucial bit to enable using this with screen

用法(在 script.sh 中进一步)

现在我们可以做

timeslots='00_XX 01_XX 02_XX 03_XX 04_XX 05_XX 06_XX'
for timeslot in $timeslots;
do 
    screen -dmS $timeslot bash -c "test_function $timeslot";
done

而且它有效。

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