0

I have a script getInfo.sh I made in Linux that collects information about the user, date, number of users logged into current environment, and many other features.

I could easily outside of the file have something where it is ./getInfo.sh > results.txt.

However I would like this to happen automatically within the script.

If I were to include the ./getInfo.sh > results.txt within the script itself it would create an infinite loop as each time it hits the ./getInfo.sh it will re-run the script and create an infinite loop.

Any alternatives here?

accdias
  • 5,160
  • 3
  • 19
  • 31
Pablo J
  • 1
  • 1
  • Add `exec 2>&1>results.txt &` as the first command in your script. – accdias Feb 03 '20 at 02:22
  • Or, just redirect each of the outputs of the script to your new file, e.g. `echo "something important" >> newfile` - you can pass the output file as a parameter or write to a default name if no argument is provided. – David C. Rankin Feb 03 '20 at 02:23
  • 1
    Correcting my previous comment: add `exec 2>&1>& results.txt` as the first command in your script. That will redirect all output (errors included), to `results.txt`. If you want errors messages still be printed to console, use this instead `exec 1>& results.txt`. – accdias Feb 03 '20 at 02:30

1 Answers1

0

If you want to output everythig including errors, put this as the first command in your script:

exec 2>&1>& results.txt

If you want don't want the errors to be in the file and instead have them outputted to the console, then add this as the first command in your script:

exec 1>& results.txt

Some extras...

If you want to have the everything not including errors outputted to a file and shown in the console, then add this as the first command in your script:

exec > >(tee -ia results.txt)

If you want also want the errors outputted to a file and shown in the console, then add the command shown above and this command to the start of your script:

exec 2> >(tee -ia errors.txt)

Credits to @accdias for the first solution

Credits to @Paused until further notice. for the second solution: https://superuser.com/a/86955/1040587

Siddharth Dushantha
  • 1,391
  • 11
  • 28