在 bash 脚本中实现干 运行

Implementing dry run in a bash script

我正在寻找一种在我的 bash 脚本中实现干 运行 的优雅方法。 我找到了多种方法来做到这一点,但其中 none 符合我的需要。

其中一个包括编写一个干燥的运行函数,就像这里建议的那样: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

当然,这将 运行 命令第一部分的函数(即 tar),并将此函数的结果提供给 7z。 不是我想要的。

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

由于您正在使用管道,因此您需要为该行中的所有命令添加“$DRYRUN”。如果你只是在所有命令前添加 $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