开发者

Trying to redirect output of shell script to file and stdout. cd command in the script causes weird behaviour

Here is the situation:

I have a shell script - script.ksh

I am calling it from a java program and I need the stdout from the script in the java program.

I also need to redirect the output to a file and if the script fails at any point, I have to send a mail with the file attached to it.

so the file must be closed before the script exits so that the mailer can send it.

I have got everything working right.

Except for 1 thing - if there is any 'cd' statement in the script the file doesn't get closed before the script ends. Please help me out here

Not sure why this is happening.

Here's a simplified version of the code.

#!/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 th开发者_如何学JAVAe 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


You are opening files in the current directory and then changing directories. Try using absolute paths for those files.

Why are you piping echo through cat? It has no effect in your script. Just cat the file. There's no need to redirect stdout to stdout either. cat file is the same as cat file >&1.

Why are you doing exit 1 for a normal exit. I should be exit 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜