Why do I get different bash script results when called with 'set -x' and how to fix it?

I found that the results of my bash script will change depending on whether I execute it using debugging or not (i.e. it calls set -x). I do not mean that I get more results, but the result itself is different.

I assume that this is not the desired behavior, and I hope that you teach me how to do it.

The bash script below is a contrived example, I tried to reduce the logic from the script that I am learning so that the problem is easily reproducible and obvious.

#!/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

.

.

When I execute without set -x, it works as I expect, as shown below:

Current diregtory is:/root
>>>>>>>> /tmp//root.flag
Match

.

.

, -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:#  
+5
3

...

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

... ...

result=$(pwd 2>&1)

... pwd , set -x.

+3

, , , , set -x, , , :

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

, 2>&1.

+4

, $PWD, , script ( -x). $PWD.

0

All Articles