How do I let my script not only output to screen but also record its output to a file? I want this to be done automatically within the script, rather than requiring the user to pipe the output through tee or some other solution.


Use tee.

script.sh < inputfile | tee logfile

  • Yes, I saw this method. But am giving input which reads a particular file from path gets output, can tee used inside script.? – Irfan Sep 13 '18 at 14:43
  • @Irfan I believe you need basic English training although I am able to guess your intention. I'll edit my answer. – 炸鱼薯条德里克 Sep 13 '18 at 14:48
  • I think they want the script itself to mirror output to stdout and a file, without the person running it needing to do anything special – Michael Mrozek Sep 13 '18 at 14:50
  • Sorry to interrupt..but I don't know why u say I need English training on this..!! I may be week on posting understandable queries,if am wrong try to correct me dont humiliate hope u know this is public forum :),anyways thanks ur query worked to me it shows in different file but I need tat to be included inside script – Irfan Sep 13 '18 at 15:18
  • @Irfan I guess, not understand. I'm still not so sure about what you're asking. If nobody can understand your question, then you're not getting an answer you need. Refuse language training leads to lack of ability of expressing your needs, which further leads to not being able get the answer you want. – 炸鱼薯条德里克 Sep 13 '18 at 15:38

You didn't specify, so I'm assuming this is a bash script. According to man bash (emphasis mine):

exec [-cl] [-a name] [command [arguments]]
If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environment. If a is supplied, the shell passes name as the zeroth argument to the executed command. If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1.

So you can use process substitution to run a copy of tee that's logging to a file, and redirect your stdout to that tee so that it prints and logs at once:

exec > >(tee /path/to/log-file)

If you also want to capture stderr, you need to merge it with stdout:

exec 2>&1

Or just capture both at once with:

exec &> >(tee /path/to/log-file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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