3

I want to redirect the output of a bash script to a file.

The script is:

#!/bin/bash
echo "recursive c"
for ((i=0;i<=20;i+=1)); do
time ./recursive
done

But if I run it like this:

script.sh >> temp.txt

only the output of ./recursive will be captured in the file.

I want to capture the output of time command in the file.

2 Answers 2

8

Redirect STDERR to STDOUT:

script.sh >> temp.txt  2>&1

Or if using bash 4.0:

$ script.sh &>> temp.txt

(Thanks for the second form go to commenter ephemient. I can't verify as I have an earlier bash.)


My tests were surprising:

$ time sleep 1 > /dev/null 2>&1

real    0m1.036s
user    0m0.002s
sys     0m0.032s

The problem is the redirection was included as part of the command to be timed. Here was the solution for this test:

$ (time sleep 1) > /dev/null 2>&1

I don't think this is part of your problem, but it seemed worth a mention.

Sign up to request clarification or add additional context in comments.

1 Comment

New in bash 4.0: script.sh &>> temp.txt does the same as above. :)
2

I prefer the &>> method better, but this is a solution as well:

$ script.sh 2>&1 |tee -a temp.txt

1 Comment

Yep, me too. You can view the output in console and have it in the file too.

Your Answer

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