1

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.

Community
  • 1
  • 1
Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • This? http://stackoverflow.com/questions/11229385/redirect-all-output-in-a-bash-script-when-using-set-x `exec > your_log_file 2>&1` You could also run the script like this: `./your_script.sh > output` – fedorqui Sep 16 '14 at 08:35
  • @fedorqui This works perfectly! However, it would be even better if I could separate outputs and errors into two files. :) – Sibbs Gambling Sep 16 '14 at 08:42

1 Answers1

2

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598