1

Bellow is a simple code:

#!/bin/bash -ef
echo "Hello" > log.txt #saving the output of this command log.txt
command1 #this command running and showing it is output in terminal
command2 > log.txt #saving the output of this command log.txt
command3 #this command running and showing it is output in terminal

If I have in the script many commands. Can I hide the output of certain commands and leave this output showing in terminal window for the rest? and at the same time how can I save the output for all the commands ( showing output or not) in log.txt

6
  • You are doing it right..am i missing something here ?
    – heemayl
    Commented Aug 6, 2015 at 19:54
  • @heemayl. Thanks! But this is for only one command line. If I have many commands in the script. How can I prevent the output of the commands from showing in terminal and instead recording it in one log file. If I add > log.txt in front of every command this will remove the output from the previous commands?
    – user88036
    Commented Aug 6, 2015 at 20:00
  • Use append redirection operator >>
    – heemayl
    Commented Aug 6, 2015 at 20:07
  • In front of every command?
    – user88036
    Commented Aug 6, 2015 at 20:09
  • @don_crissti. Exactly. This is what I meant
    – user88036
    Commented Aug 6, 2015 at 20:19

1 Answer 1

2

You can temporarily redirect output to a file like so:

exec 1> log.txt
echo -n "Hello" # Hello will be written to log.txt
# Some more commands here
# whose stdout will be
# written to log.txt
exec 1> /dev/tty # Redirect stdout back to your terminal

A more general way (in case your stdout wasn't the terminal and you want to restore it to what it originally was):

exec 3>&1 # Point a new filehandle to the current stdout
exec 1> log.txt 
echo -n "Hello" # Hello will be written to log.txt
# Some more commands here
# whose stdout will be
# written to log.txt
exec 1> &3 # Restore stdout to what it originally was
exec 3> &- # Close the temporary filehandle

Thanks to Celada's comment for pointing this out.

7
  • 1
    This is problematic if the original stdout was not the terminal. A true save&restore, or using a subshell (so you don't need to restore anything) would be preferable.
    – Celada
    Commented Aug 6, 2015 at 20:18
  • @Celada True. Thanks for the comment. I simply inferred from the OP's comments that stdout is already the terminal.
    – Joseph R.
    Commented Aug 6, 2015 at 20:21
  • 1
    One should never assume this. Even if the person writing the script (the OP in this case) expects stdout to be the terminal, the person using the script (a different person) might run the script with output redirected elsewhere and expect it to stay redirected.
    – Celada
    Commented Aug 6, 2015 at 20:24
  • @Celada You are right. Does the update help?
    – Joseph R.
    Commented Aug 6, 2015 at 20:26
  • Yes, that's exactly what I meant by a "true save&restore".
    – Celada
    Commented Aug 6, 2015 at 20:27

You must log in to answer this question.