如何验证shell脚本要运行的命令

时间:2015-02-11 10:58:04

标签: bash shell

如果我使用set -x,则命令会在执行之前显示。这样就印了。

但是我希望我的脚本具有一个调试模式,用户可以实际看到哪些命令将被打印,但这些命令不会被执行。

我还尝试使用:(空命令)来打印当前命令但不传播结果。如,

find /my/home -name "test*" | while read -r i;
do 
    rm -f $i
done

为此目的,预期的输出是:

+find /my/home -name "test"
+ rm -f test1
+ rm -f test2 ...

等等

有没有办法可以在不重复代码的情况下实现这一点(显然,批处理脚本中有2个部分用于调试和普通模式)?

2 个答案:

答案 0 :(得分:2)

你可以创建一个包装函数来打印或评估你给它的命令:

#!/bin/bash

run_command () {
   printf '%q ' "$@"
   "$@"
}

run_command ls -l
run_command touch /tmp/hello
run_command rm /tmp/hello

这样,您可以将run_command添加到您想要执行的任何操作中,并根据需要对执行或echo操作发表评论。

您还可以为脚本提供切换到echo或执行模式的参数:

debug_mode=$1
run_command () {
    if [ "$debug_mode" = true ]; then
        printf '%q ' "$@"
    else
        "$@"
    fi
}

run_command ...

答案 1 :(得分:0)

运行preview / dryrun最简单的方法:

for f in *; do echo "these files will be removed with rm -f $f"; done