加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 21:54:21 所属栏目:安全 来源:网络整理
导读:我发现我的bash脚本的结果将根据我是否使用调试执行它(即调用set -x)而改变.我并不是说我得到更多输出,但程序本身的结果不同. 我假设这不是理想的行为,我希望你能教会我如何纠正这个问题. 下面的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

.

.

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

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:#

解决方法

改变…

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

… INTO …

result=$(pwd 2>&1)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读