0

情况如下:

我有一个 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
4

1 回答 1

1

您正在打开当前目录中的文件,然后更改目录。尝试对这些文件使用绝对路径。

你为什么要echo通过管道cat?它对您的脚本没有影响。只是cat文件。也不需要将标准输出重定向到标准输出。cat file是一样的cat file >&1

你为什么要exit 1正常退出。我应该是exit 0

于 2011-02-04T07:41:41.563 回答