切换用户后Bash函数无法访问外部变量的问题
问题原因与解决方案
问题根源
你遇到的问题是因为logtime是当前shell的局部变量,没有被导出到环境变量中。虽然你用export -f runcommand导出了函数,但函数执行时会在userA的shell环境中查找$logtime,而这个环境里并没有这个变量,所以输出为空。
注意:脚本里的compile-$logtime.txt文件名能正常生成,是因为这个$logtime是在当前shell中展开的,不是userA的shell环境处理的。
解决方案
方案1:导出logtime为环境变量
将logtime变量导出,让userA的shell环境能读取到它:
logtime=$(date +"%Y-%m-%d_%H%M%S") export logtime # 把变量导出到环境中 runcommand() { echo " Log time is $logtime" } export -f runcommand su userA -c "bash -c runcommand >> compile-$logtime.txt"
方案2:将logtime作为参数传递给函数
把变量值通过参数传递给函数,避免依赖环境变量:
logtime=$(date +"%Y-%m-%d_%H%M%S") runcommand() { echo " Log time is $1" # 用第一个参数接收logtime值 } export -f runcommand su userA -c "bash -c 'runcommand $logtime' >> compile-$logtime.txt"
方案3:在userA的shell中直接定义logtime
在执行函数前,先在userA的shell里定义变量:
logtime=$(date +"%Y-%m-%d_%H%M%S") runcommand() { echo " Log time is $logtime" } export -f runcommand su userA -c "bash -c 'logtime=$logtime; runcommand' >> compile-$logtime.txt"
内容的提问来源于stack exchange,提问作者Mathew Shiju
相关产品推荐
相关产品推荐

