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.

2
  • This? stackoverflow.com/questions/11229385/… exec > your_log_file 2>&1 You could also run the script like this: ./your_script.sh > output Commented Sep 16, 2014 at 8:35
  • @fedorqui This works perfectly! However, it would be even better if I could separate outputs and errors into two files. :) Commented Sep 16, 2014 at 8:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

This is awesome! Thanks a lot for the quick and sweet solution!
You are welcome :) I didn't know about it, so both of us learnt a nice thing today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.