source /etc/profile 引发的问题
问题描述:
在脚本中调用了source /etc/profile,脚本出现了很奇怪的问题,还没有经过初始化的函数运行了多次,导致部分变量没有获取,脚本执行失败。
代码示例:
#!bin/sh
test(){
#do something
}
init_param(){
}
main(){
source /etc/profile
init_param
test
}
main
奇怪的是将source /etc/profile > /dev/null 2>&1之后就不会有报错信息,去除source 也没有问题,那就是由source /etc/profile 导致的。
使用salt "ip" cmd.run "sh test.sh" 就会出问题,直接在本机上执行sh test.sh 就不会报错。
问题定位:
使用-x 显示执行过程,salt "ip" cmd.run "sh -x test.sh" ,发现在source /etc/profile的时候直接调用了我的脚本中的test函数,而此时我的这个test函数还没到该调用的时候。

原来是source /etc/profile 的时候,会调用一些脚本,这些脚本中就会调用test这个函数,这就是没经过init_param函数就直接执行test的原因,并且由于是循环调用,所以test会执行很多遍。
问题根因:
- soure /etc/profile 应该放在第一行,否则自定义的函数声明后有可能与自定义的函数重名。
- 自定义的test函数与系统的函数重名,自定义函数命名应该复杂一点,有具体的含义。

浙公网安备 33010602011771号