情况是这样的:
我有一个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发布于 2011-02-04 15:41:42
您正在打开当前目录中的文件,然后更改目录。尝试使用这些文件的绝对路径。
为什么你要通过cat传输echo?它在您的脚本中不起作用。只需对文件执行cat操作。也不需要将stdout重定向到stdout。cat file与cat file >&1相同。
为什么要在正常退出时执行exit 1。我应该是exit 0。
https://stackoverflow.com/questions/4895025
复制相似问题