0

Currently I have a script where I want all output to be redirected to both a file and the console.

#!/bin/bash
touch /mnt/ybdata/ybvwconf.log 
{
  ... [Do some script code here]
} 2>&1 | tee -a /mnt/ybdata/ybvwconf.log 

Above, you can see my current code, which works perfectly fine. It prints all the output to the console as well as piping it to the ybvwconf.log file. However, I was looking for a way to eliminate the curly brackets. Something along the lines of this:

#!/bin/bash
touch /mnt/ybdata/ybvwconf.log
exec 2>&1 | tee -a /mnt/ybdata/ybvwconf.log

... [Do some script code here] 

I have tried this approach and sadly it does not work. I don't get any errors but no content appears in my log file. Any ideas what might be wrong?

Kristianasp
  • 61
  • 11
  • 1
    Why do you want to eliminate the curly brackets? – 123 Jun 06 '17 at 12:16
  • You don't need to `touch` first – Attie Jun 06 '17 at 12:56
  • Possible duplicate of [redirect COPY of stdout to log file from within bash script itself](https://stackoverflow.com/questions/3173131/redirect-copy-of-stdout-to-log-file-from-within-bash-script-itself) – DevSolar Jun 06 '17 at 13:51

1 Answers1

1

You can place this at top of your script to redirect both stdout and stderr to a file and show them on terminal as well.

#!/bin/bash
exec &> >(tee /mnt/ybdata/ybvwconf.log; exit)

# your script code goes here
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This does not seem to work as intended when I run it. It gives an error: `No such file or directory/dev/fd/62` – Kristianasp Jun 06 '17 at 12:29
  • Is `/mnt/ybdata/` a valid and accessible directory for your script? Try this to test: `exec &> >(tee /tmp/ybvwconf.log; exit)` – anubhava Jun 06 '17 at 12:35
  • Yep it is. I tried with `/tmp/ybvwconf.log` as well and I am getting the same error at the start of the script. – Kristianasp Jun 06 '17 at 12:45
  • You have some strange permission issue because this is working fine in my bash and creates `/tmp/ybvwconf.log` every time I run this script. – anubhava Jun 06 '17 at 12:48
  • Hmm, strange. I'll poke around a bit and see if I can find out why. Might be something to do with the VM I am running the script on. – Kristianasp Jun 06 '17 at 12:57