简体   繁体   English

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

[英]How to verify the commands to be run by shell script

If I use set -x , then the commands are displayed just before they are executed. 如果我使用set -x ,那么命令将在执行之前显示。 That way they are printed. 这样就可以打印它们。

But I want to have a debug mode for my script where the user can actually see what commands are going to get printed but those are not executed. 但是我想为我的脚本设置一个调试模式,在该模式下,用户可以实际看到要打印的命令,但是不会执行。

I also tried using : (null command) to print the current command but that does not propagate the result. 我也尝试使用:空命令)打印当前命令,但是不会传播结果。 eg, 例如,

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

For this purpose, the out put expected is: 为此,预期的输出为:

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

and so on 等等

Is there any way I can achieve this without repeating code (the obvious way being have 2 sections in the batch script for debug and normal mode)? 有什么方法可以实现而无需重复代码(明显的方法是批处理脚本中有2个部分用于调试和正常模式)?

You can maybe create a wrapper function that either prints or evaluates the command you give to it: 您也许可以创建一个包装函数,该函数可以打印或评估您提供给它的命令:

#!/bin/bash

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

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

This way, you prepend run_command to any single thing you want to do and comment the execution or the echo action as you wish. 这样,您可以在run_command要执行的任何操作,并根据需要注释执行或echo操作。

You could also provide a parameter to the script that switches to either echo or execute mode: 您还可以为脚本提供一个参数,该参数可以切换为echo或execute模式:

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

run_command ...

运行预览/ dryrun的最简单方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM