Redirection
Standard Output
- frequently abbreviated as stdout
- redirection represented with
> - used to redirect the result of a command somewhere else
- the contents of the file are overwritten when using
> - can use
>>to append to the contents of a file
Examples
Output the results of one command to a file
echo "print('hello world')" > hello.pyOutput and concatenate the results to a new line in the file
echo "print('another line')" >> hello.pyOutput but erase the contents of
hello.pyecho "print('erase that old stuff')" > hello.py
Standard Input
- frequently abbreviated as stdin
- redirection represented with
< - can be used to provide input into a program
Example
Create a file named
name.txtthat contains your name.echo "josh" > name.txt # create a file named name.txt that contains your nameOpen a text editor
vim greeting.py # or nano greeting.pyAdd the following code to the file.
import sys name = sys.stdin.read() print(f"Hi {name}")Save and close the file.
Feed the contents of the
name.txtfile into thegreeting.pyfile while running the python file.python3 greeting.py < name.txt
Standard Error
- Frequently abbreviated as stderr
- represented with
2> - can append with
2>> - if an error is produced, you can use this to redirect the error elsewhere, like a log file for errors
Examples
notarealcommand 2> error-file.txt
notarealcommand 2>> error-file.txtPipe
- represented with
| - creates a “pipe” or “pipeline” between two programs
- takes the output of the one command and uses it as input it into another command
Example
List the contents of /usr/bin, but use more to view them in a paginated way.
ls -al /usr/bin | more