How to redirect stderr to a file as well

Hello everyone,

I'm a nooby in Linux, and I need some help.

I have a shell script like this:

echo "Start of script" > ../My_Log_Dir/Script_Name.log
 
..
 
cp ../My_DataIn/File.txt ../My_DataOut/ 2>> ../My_Log_Dir/Script_Name.log
 
rc=$?
 
..
 
echo "End of Script" >> ../My_Log_Dir/Script_Name.log
 
exit rc
 
 

And I execute the Shell like this:

../My_Shell_Dir/./My_Shell 2>../My_Log_Dir/Temp.log

Later I'll need to read Temp.log so I want it with all the error display's. But as I'm not getting the error display from de cp command. A tryed with the tee command and it worked, but I lost the return code from de cp command.

My idea here is to put the error display in a log file (used in other processes) and still keep it in the stderr. In this way I could use it when I invoque the shell script.

Hope someone can help!

Thank's!

What do you want? errors and stdout in same file? or errors in one stdout in another?

1 Like
../My_Shell_Dir/./My_Shell 2>../My_Log_Dir/Temp.log

I dont get... Am I to tired and not seeing the obvious or is there some typos errors (the use of slash-dot-slash)

1 Like

Instead of redirecting stdout and stderr of every command in your script...why dont you just do it once on the command line when you are executing it...

echo "Start of script"
..
cp ../My_DataIn/File.txt ../My_DataOut/
..
rc=$?
..
echo "End of Script"
.. 
exit rc

Thats your script with all the stdout and stderr redirection taken out...now when you run it on the comand line just do it as...

../My_Shell_Dir/./My_Shell >../My_Log_Dir/Temp.log 2>&1

this will send stdout and stderr of every command in your script to Temp.log and you wont lose the return code from any command either.

1 Like

I want two things:

  1. to produce a log file during the execucion of the script with some output made by myself (the echo cases) and the errors from stderr (from the cp command);
  2. I also need the errors to been set in stderr, so when I execute the shell script in temp.log I get in temp.log error from the cp command (if any) and errors if its not possible to execute the script, because I'm runing the script from a SAS Script in other environment.

Like this I would have 2 log files. One with the execution log (Script_name.log) and some explanations and the other (Temp.log) only with the errors, that I will read after and print that out, if there is any.

As I said erlier I can't perform a tee command because I'll get the return command from tee and not the cp command.

That is why Shamrock solution doesn't fit.

Thank's everyone.

Like this?

../My_Shell_Dir/./My_Shell >../My_Log_Dir/My_Shell.log 2>../My_Log_Dir/Temp.log 

Output logs in My_Shell.log
Error logs in Temp.log

--ahamed