Kanishka Khandelwal
Kanishka Khandelwal

Reputation: 134

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. 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. e.g.,

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)?

Upvotes: 1

Views: 661

Answers (2)

klerk
klerk

Reputation: 371

Most simplest way to run preview/dryrun:

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

Upvotes: 0

fedorqui
fedorqui

Reputation: 289735

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.

You could also provide a parameter to the script that switches to either echo or execute mode:

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

run_command ...

Upvotes: 2

Related Questions