我正在寻找一种优雅的方式来在我的一个 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
当然,这将在命令的第一部分(即 tar)运行该函数,并将该函数的结果提供给 7z。
不是我要找的。
也许与 eval 命令有关,但我仍然无法弄清楚如何实现它......
任何的想法 ?
最佳答案
由于您正在管道中,您需要为该行中的所有命令设置“$DRYRUN”。如果您只是在所有命令前添加 $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
关于bash - 在 bash 脚本中实现试运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50002555/