Wednesday, November 9, 2016

Bash command redirections

There are 3 file descriptors, stdin, stdout and stderr (std=standard).

Available options:
  1. redirect stdout to a file
  2. redirect stderr to a file
  3. redirect stdout to a stderr
  4. redirect stderr to a stdout
  5. redirect stderr and stdout to a file
  6. redirect stderr and stdout to stdout
  7. redirect stderr and stdout to stderr
  8. 1 'represents' stdout and 2 stderr.
Note: with the less command you can view both stdout (which will remain on the buffer) and the stderr that will be printed on the screen, but erased as you try to 'browse' the buffer.

Sample: stdout to file

This will cause the ouput of a program to be written to a file.

         ls -l > stdout.txt
        
Here, a file called 'stdout.txt' will be created and it will contain what you would see on the screen if you type the command 'ls -l' and execute it.

Sample: stderr 2 file

This will cause the stderr output of a program to be written to a file.

          ls -l 2> stderr.txt
        
Here, a file called 'stderr.txt' will be created and it will contain what you would see the stderr portion of the output of the ' ls -l' command.

Sample: stdout 2 stderr

This will cause the stderr ouput of a program to be written to the same filedescriptor than stdout.

          ls -l 1>&2 
        
Here, the stdout portion of the command is sent to stderr, you may notice that in different ways.

Sample: stderr 2 stdout

This will cause the stderr ouput of a program to be written to the same filedescriptor than stdout.

          ls -l 2>&1
        
Here, the stderr portion of the command is sent to stdout, if you pipe to less, you'll see that lines that normally 'dissappear' (as they are written to stderr) are being kept now (because they're on stdout).

Sample: stderr and stdout 2 file

This will place every output of a program to a file. This is suitable sometimes for cron entries, if you want a command to pass in absolute silence.

          ls -l &> /dev/null 
        
This (thinking on the cron entry) will delete every file called 'core' in any directory. Notice that you should be pretty sure of what a command is doing if you are going to wipe it's output.

No comments:

Post a Comment