情况如下:
我有一个 shell 脚本 - script.ksh
我从一个java程序调用它,我需要java程序中脚本的stdout。
我还需要将输出重定向到一个文件,如果脚本在任何时候失败,我必须发送一封附有文件的邮件。
因此必须在脚本退出之前关闭文件,以便邮件程序可以发送它。
我让一切正常。
除了一件事 - 如果脚本中有任何“cd”语句,则文件在脚本结束之前不会关闭。请帮帮我
不知道为什么会这样。
这是代码的简化版本。
#!/bin/ksh
#Need to redirect output to file and stdout
exec 6>&1 #save stdout in [6]
exec 1>shell.log 2>&1 #redirect stderr and stdout to file
#if any error happens reset stdout and print the log contents
trap '
echo "Error Trap";
exec 1>&- 1>&6 6>&-;
echo | cat shell.log>&1;
echo "send the log file by mail";
exit 1' ERR
#cd / #Uncomment and the script behaves differently
echo "some task"
./somescript.ksh #this requires me to cd to its directory and then execute
trap - ERR #End the ERR trap
#in case of normal exit print the log contents
trap '
echo "Normal Exit"
exec 1>&- 1>&6 6>&-;
echo | cat shell.log>&1;
exit 1' EXIT