美文网首页
Shell使用输出重定向时发现的问题总结

Shell使用输出重定向时发现的问题总结

作者: 努力2009 | 来源:发表于2016-12-22 19:24 被阅读570次

    在调用函数时,如果使用tee做输出重定向,会造成在函数内对全局变量的修改,出函数之后失效。

    不使用tee做输出重定向的代码:

    #!/bin/bash
    declare -i NUM=100;
    function updateNum(){
      echo "updateNUm: before update 'NUM'=$NUM"
      NUM=300;
      echo "updateNUm: after update 'NUM'=$NUM"
    }
    
    echo "调用函数之前,NUM=$NUM";
    updateNum 2>&1 >> /home/shangsong/temp/test1.log;
    echo "调用函数之后,NUM=$NUM";
    

    执行“bash -x test1.sh”

    + declare -i NUM=100
    + echo 调用函数之前,NUM=100
    调用函数之前,NUM=100
    + updateNum
    + echo 'updateNUm: before update '\''NUM'\''=100'
    + NUM=300
    + echo 'updateNUm: after update '\''NUM'\''=300'
    + echo 调用函数之后,NUM=300
    调用函数之后,NUM=300
    

    使用tee做输出重定向之后的代码:

    #!/bin/bash
    declare -i NUM=100;
    function updateNum(){
      echo "updateNUm: before update 'NUM'=$NUM"
      NUM=300;
      echo "updateNUm: after update 'NUM'=$NUM"
    }
    
    echo "调用函数之前,NUM=$NUM";
    updateNum 2>&1 | tee /home/temp/test1.log;
    echo "调用函数之后,NUM=$NUM";
    

    执行“bash -x test1.sh”

    + declare -i NUM=100
    + echo 调用函数之前,NUM=100
    调用函数之前,NUM=100
    + updateNum
    + tee /home/shangsong/temp/test1.log
    + echo 'updateNUm: before update '\''NUM'\''=100'
    updateNUm: before update 'NUM'=100
    + NUM=300
    + echo 'updateNUm: after update '\''NUM'\''=300'
    updateNUm: after update 'NUM'=300
    + echo 调用函数之后,NUM=100
    调用函数之后,NUM=100
    

    结论

    在调用函数时,如果使用tee做输出重定向,会造成在函数内对全局变量的修改,出函数之后失效。

    相关文章

      网友评论

          本文标题:Shell使用输出重定向时发现的问题总结

          本文链接:https://www.haomeiwen.com/subject/khshvttx.html