5

This question already has an answer here:

I've a bash script that call various commands and prints some output (both from the called commands themselves, such as git pull, and informative messages generated by the script itself such as Operation took XX minutes.

I'd like to capture the whole output to a file from the script itself: basically I'm trying to avoid the need to call the ./myscript.sh > file.txt for non-relevant-here reasons.

Basically I'd like to do something like this:

startCapture

git pull

echo "Text"

other-command

endCapture

Plus, I also require the output to be printed on my shell while the script is running.

The final goal is to:

  1. run ./myscript.sh without additional shell construct
  2. see the output on the terminal as I do now
  3. obtain file on disk with the whole output

Is this even possible?

marked as duplicate by Patrick, DopeGhoti, ilkkachu bash Feb 16 '18 at 18:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

You want to use tee.

Ex:

echo "Hello World" | tee out.txt

This creates a file out.txt with the output from the command and prints it to the screen. Use "tee -a filename" if you want to append to the file.

echo "Hello" | tee -a out.txt
echo "World" | tee -a out.txt

out.txt will have two lines Hello and World (without -a it would only have world)

If you want to save the entire script and output the entire script:

./script.sh | tee output.txt
1

A method I found to capture all output from any session is to start a new bash session and tee to a log file. its really useful for tracking more then just a script.

bash | tee ~/bash.log #this will save standard output until the bash session is ended
bash | tee ~/bash.log  2>&1 #this will save all output including errors until the bash session is ended

or you can just tee the script it's self

./myscript.sh | tee ./myscript.log #this will log only the output of the script.

  • Your solution addresses STDOUT, but not STDERR – user1404316 Feb 16 '18 at 17:28
  • I put in an example with 2>&1 – thebtm Feb 16 '18 at 17:31
1

You can always invoke script inside a script to log everything.

As to print and log everything at the same time in a bash script to log.txt:

#!/bin/bash

if [ -z "$SCRIPT" ]
then 
    /usr/bin/script log.txt /bin/bash -c "$0 $*"
    exit 0
fi

echo teste

Seeing the log log.txt:

$ ./a.sh
Script started, output file is log.txt
teste

Script done, output file is log.txt
$ cat log.txt
Script started on Fri Feb 16 17:57:26 2018
command: /bin/bash -c ./a.sh 
teste

Script done on Fri Feb 16 17:57:26 2018

Not the answer you're looking for? Browse other questions tagged or ask your own question.