Instead of putting >>
at the end of each command such as:
date >> newfile
ls >> newfile
# etc.
How would I take the entire output of a script and put it into a file without the need for multiple appends, such as in the following code?
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