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

2016-12-22  本文已影响570人  努力2009

在调用函数时,如果使用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做输出重定向,会造成在函数内对全局变量的修改,出函数之后失效。

上一篇 下一篇

猜你喜欢

热点阅读