Sibbs Gambling
Sibbs Gambling

Reputation: 20355

Specify one output file and another error file for the whole shell script?

I wish to have one file output.txt to hold all the outputs of my shell script. Similarly, a error.txt file to hold all the errors of my shell script.

I understand that technically, I can achieve this by manually appending >>output.txt to every line that prints out something. However, I feel that very ugly. I vaguely remember something like

#!/bin/sh
#$ -o ./output.txt
#$ -e ./error.txt

echo Hello World!

may work. However, it is somehow not working when I try it out.

So, how can I specify one output file that automatically absorbs all the outputs?

Update

This question may seem like a duplicate of this one. Yet, one difference is that I also wish to separate outputs and errors into two separate files.

Upvotes: 1

Views: 655

Answers (1)

fedorqui
fedorqui

Reputation: 289635

As seen in redirect all output in a bash script when using set -x, you can use this approach:

exec > log_file 2>&1

If you want to specify different files for stdin and stderr, do:

exec 2> log_error 1> log_output

Test

#!/bin/bash

exec 2> error 1> mylog
echo "hello this is this"
ls alsdjflask

and we get...

$ ./a
$ cat mylog 
hello this is this
$ cat error 
ls: cannot access alsdjflask: No such file or directory

Upvotes: 2

Related Questions