Redirect STDOUT And Other File Descriptors To A File in Bash

(0 votes, average 0 out of 5)

It is possible to redirect the output of a single command in Bash to a file using the > convention. For example, to redirect the STDOUT output to a file, use:

 

ls -l > myfile.txt

 

 

However sometimes it would be better to redirect all output from multiple commands to a single file. This can be used by modifying the file descriptor, 1. First, we save a backup of the file handle for STDOUT and then change it to point to the desired file. We can then later restore STDOUT from the backup:

1
2
3
4
5
6
exec 6>&1           # Link file descriptor #6 with stdout (saves STDOUT)
exec > myfile.txt   # stdout replaced with file
 
echo "this will be outputted to myfile.txt instead of the console (STDOUT)"
 
exec 1>&6 6>&-      # Restore stdout and close file descriptor #6.

This can be very useful for logging output of a script. 1 is the file descriptor for STDOUT and 2 is the file descriptor for STDERR so you can modify each as appropriate - for example send logging to one file and errors to another file.

Partner Links:
Last Updated on Tuesday, 15 March 2011 12:19  
Related Articles

» How to Enable Playback of MKV Files in Windows 7 Media Center

Back up your registry and create a system restore point. This is in case any problems arise in the process. the Windows 7 version of the codec pack. (The actual download is hosted by Major Geeks). When the download completes, install the codec pack.If you are running the 64-bit version of Windows 7, download and install those components as well. the MKV Registry Hack for your version of Windows 7 (32 or 64 bit).Double click the downloaded .reg file and allow the process to complete. This will...

» Mount a WebDAV filesystem (like box.net) on Linux using davfs2

You can easily mount a WebDAV filesystem on Linux so that you can access the files just like they were on your local computer. One way to do is to install the davfs2 package (this is the Ubuntu/Debian package name, though it should be similar for other distros). Once you have installed it, add an entry to /etc/davfs2/secrets with your login credentials for the WebDAV account. For box.net, the command would look like this:sudo echo “https://www.box.net/dav username password” >>...

» Copy or Backup Files Faster in Windows 7 or Vista Using Window's Robocopy

In all versions of Windows 7 there is a little known but easy to use utility bundled in called Robocopy.  Why would you want to use Robocopy over just dragging and dropping or copying and pasting files and folders over manually? Here are some reasons why you might want to add Robocopy to your toolbox of useful utilities:Robocopy is MUCH faster at copying a large number of files from one location to another compared to the built in Windows copy.Robocopy can intelligently "Backup" (Mirror) a...