用bash脚本实现干式运行



我正在寻找一种优雅的方式来在我的一个bash脚本中实现干式运行。我找到了多种方法,但是它们都不适合我的需求。

其中之一是写下干燥功能,如下所示:https://gist.github.com/pablochacin/32442fbbdb99165d6f7c

但是我要执行的某些命令包括管道,此方法不兼容管道。例如,我想在干式运行中执行此操作:

tar cf - drytestfile | 7z a -m0=lzma2 -mx=9 -mmt=$nbCores -si drytestfile.tar.7z | tee -a /tmp/testlog

使用上面的方法,我将在脚本中使用此方法,其中$ dryrun包含执行所有参数的函数的名称:

$DRYRUN tar cf - drytestfile | 7z a -m0=lzma2 -mx=9 -mmt=$nbCores -si drytestfile.tar.7z | tee -a /tmp/testlog

当然,这将在命令的第一部分(含义焦油(运行该功能,并以此功能为FEED 7Z。并不是我要寻找的。

也许与eval命令有关,但我无法弄清楚如何实现...有什么想法吗?

由于您要管道,因此需要为行中的所有命令提供" $ dryrun"。如果您只在所有命令的前面添加$ dryrrun,那么它将起作用,但是您只会看到最后一个命令的输出。如果要显示所有命令,一种方法是更改Dryrun函数,即(编辑Charles Duffy评论(:

dryrun() {
    if [[ ! -t 0 ]]
    then
        cat
    fi
    printf -v cmd_str '%q ' "$@"; echo "DRYRUN: Not executing $cmd_str" >&2
}

然后您可以做:

$DRYRUN tar cf - drytestfile | 
$DRYRUN 7z a -m0=lzma2 -mx=9 -mmt=$nbCores -si drytestfile.tar.7z | 
$DRYRUN tee -a /tmp/testlog

例如:

dryrun echo "hello" | 
dryrun echo "world" | 
dryrun echo "foo" | 
dryrun echo "bar"

将产生:

DRYRUN: Not executing command echo hello
DRYRUN: Not executing command echo world
DRYRUN: Not executing command echo foo
DRYRUN: Not executing command echo bar

相关内容

最新更新