Home > Back-end >  How to append all output from a linux script in to a new file
How to append all output from a linux script in to a new file

Time:09-16

Instead of putting a >> at the end of each command such as:

date >> newfile

ls >> newfile

etc.

How would I take the entire output of a script and move it in to a file without the need for multiple appends?

such as :

date

ls

echo $USER

">> new file"

CodePudding user response:

I found a solution to this.

I was able to execute the script.sh file and simply redirect the output to a new file.

example:

./Script.sh > newfile.txt

CodePudding user response:

You can use exec to redirect the output of the script (and hence any commands executed in the script):

#!/bin/sh

exec >> newfile  # Direct all output to newfile
date
ls
echo "$USER"

or you can redirect a block of commands:

#!/bin/sh

{
    date
    ls
    echo "$USER"
} >> newfile

You can also redirect to a file for some commands and restore for others:

#!/bin/sh

exec 3>&1
exec > newfile
echo this output is written to newfile
exec >&3
echo this outupt goes to the original stdout
  • Related