使用'set -x'调用时,为什么会得到不同的bash脚本结果,如何解决?

Joh*_*cha 5 bash

我发现我的bash脚本的结果会改变,具体取决于我是否通过调试执行它(即调用set -x).我并不是说我得到更多输出,但程序本身的结果不同.

我假设这不是理想的行为,我希望你能教会我如何纠正这个问题.

下面的bash脚本是一个人为的例子,我尝试从我正在调查的脚本中减少逻辑,以便问题可以很容易地重现和显而易见.

#!/bin/bash

# Base function executes command (print working directory) stores the value in
# the destination and returns the status.
function get_cur_dir {
    local dest=$1
    local result

    result=$((pwd) 2>&1)
    status=$?

    eval $dest="\"$result\""
    return $status
}

# 2nd level function uses the base function to execute the command and store
# the result in the desired location. However if the base function fails it
# terminates the script. Yes, I know 'pwd' won't fail -- this is a contrived
# example to illustrate the types of problems I am seeing.
function get_cur_dir_nofail {
    local dest=$1
    local gcdnf_result
    local status

    get_cur_dir gcdnf_result
    status=$?
    if [ $status -ne 0 ]; then
        echo "ERROR: Command failure"
        exit 1
    fi

    eval dest="\"$gcdnf_result\""
}


# Cause blarg to be loaded with the current directory, use the results to
# create a flag_file name, and do logic with the flag_file name.
function main {
    get_cur_dir blarg

    echo "Current diregtory is:$blarg"

    local flag_file=/tmp/$blarg.flag

    echo -e ">>>>>>>> $flag_file"

    if [ "/tmp//root.flag" = "$flag_file" ]; then
        echo "Match"
    else
        echo "No Match"
    fi
}


main
Run Code Online (Sandbox Code Playgroud)

.

.

当我执行没有set -x它按预期工作时,如下图所示:

Current diregtory is:/root
>>>>>>>> /tmp//root.flag
Match
Run Code Online (Sandbox Code Playgroud)

.

.

但是,当我使用-x添加调试输出时它不起作用,如下图所示:root @ psbu-jrr-lnx:#bash -x /tmp/example.sh

+ main
+ get_cur_dir blarg
+ local dest=blarg
+ local result
+ result='++ pwd
/root'
+ status=0
+ eval 'blarg="++ pwd
/root"'
++ blarg='++ pwd
/root'
+ return 0
+ echo 'Current diregtory is:++ pwd
/root'
Current diregtory is:++ pwd
/root
+ local 'flag_file=/tmp/++ pwd
/root.flag'
+ echo -e '>>>>>>>> /tmp/++ pwd
/root.flag'
>>>>>>>> /tmp/++ pwd
/root.flag
+ '[' /tmp//root.flag = '/tmp/++ pwd
/root.flag' ']'
+ echo 'No Match'
No Match
root@psbu-jrr-lnx:#  
Run Code Online (Sandbox Code Playgroud)

Joa*_*son 3

改变...

result=$((pwd) 2>&1)
Run Code Online (Sandbox Code Playgroud)

...进入...

result=$(pwd 2>&1)
Run Code Online (Sandbox Code Playgroud)

...将允许您捕获 的输出,pwd而不捕获 生成的调试信息set -x