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?

3
  • Add exec 2>&1>results.txt & as the first command in your script. Commented Feb 3, 2020 at 2: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. Commented Feb 3, 2020 at 2: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. Commented Feb 3, 2020 at 2:30

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.