在 bash 脚本中实现试运行

And*_*iuc 20 bash

如何在 bash 脚本中实现试运行选项?

我可以考虑将每个命令都包含在 if 中并回显该命令,而不是在脚本以试运行方式运行时运行它。

另一种方法是定义一个函数,然后通过该函数传递每个命令调用。

就像是:

function _run () {
    if [[ "$DRY_RUN" ]]; then
        echo $@
    else
        $@
    fi
}

`_run mv /tmp/file /tmp/file2`

`DRY_RUN=true _run mv /tmp/file /tmp/file2`
Run Code Online (Sandbox Code Playgroud)

这是错误的,有更好的方法吗?

Ste*_*ski 5

我想玩弄@Dennis Williamson 的答案。这是我得到的:

Run () {
    if [ "$TEST" ]; then
        echo "$*"
        return 0
    fi

    eval "$@"
}
Run Code Online (Sandbox Code Playgroud)

eval "$@"这里很重要,并且比简单地做更好$*$@返回所有参数并$*返回没有空格/引用的所有参数。

$ mkdir dir
$ touch dir/file1 dir/file2
$ FOO="dir/*"
$ TEST=true Run ls -l $FOO
ls -l dir/file1 dir/file2
$ Run ls -l $FOO
-rw-r--r--  1 stefanl  stefanl  0 Jun  2 21:06 dir/file1
-rw-r--r--  1 stefanl  stefanl  0 Jun  2 21:06 dir/file2
Run Code Online (Sandbox Code Playgroud)