1

Our shell script contains the header

#!/bin/bash -x

that causes the commands to also be listed. Instead of having to type

$ ./script.sh &> log.txt

I would like to add a command to this script that will log all following output (also) to a log file. How this is possible?

1 Answer 1

6

You can place this line at the start of your script:

# redirect stdout/stderr to a file
exec &> log.txt

EDIT: As per comments below:

#!/bin/bash -x

# redirect stdout/stderr to a file and still show them on terminal
exec &> >(tee log.txt; exit)
Sign up to request clarification or add additional context in comments.

4 Comments

Do you mean I have to replace the #!/bin/bash -x with exec &> log.txt? If yes, how is ensured /bin/bash is launched?
@ThomasS no you don't
Just after #!/bin/bash -x line insert exec &> log.txt
Would exec 2>&1 | tee log.txt do the same, but also continue printing?

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.