Every program you run from the shell starts with three open channels: standard input, standard output and standard error. This lesson is about the second one, stdout, where a program writes its normal results.
Where output goes by default
stdout is normally connected to your terminal, so you see results on screen.
$ echo Hello
Helloecho does not know about screens. It writes to stdout, and the shell decides where stdout points. Each channel has a number called a file descriptor, and stdout is number 1.
Send output to a file with >
The > operator tells the shell to connect stdout to a file.
$ echo Hello > greeting.txt
$ cat greeting.txt
HelloNothing appeared after the first command because the text went into the file. If the file does not exist, the shell creates it. If it does exist, its old contents are erased first.
$ echo Goodbye > greeting.txt
$ cat greeting.txt
Goodbye1> means exactly the same as >. The 1 is simply left out most of the time.
Append with >>
Use >> to add to the end of a file and keep what is already there.
$ echo "See you" >> greeting.txt
$ cat greeting.txt
Goodbye
See youThis is the safer choice for logs and notes.
The shell acts first
The shell sets up redirection before the command starts. The file is therefore emptied even if the command then fails or does not exist. It also means you should never read and write the same file like this:
$ sort names.txt > names.txtThe shell empties names.txt, then sort reads an empty file. Your data is gone.
In Bash you can protect existing files with set -o noclobber. After that, > refuses to overwrite a regular file, and >| overrides the protection when you really mean it.
You can practise this safely in the streams and text lab.
Try it
- Run
date > log.txt, thencat log.txt. - Run
date >> log.txttwice and count the lines. - Run
date > log.txtonce more. How many lines remain? - Run
ls /etc > listing.txtand read it withless listing.txt. Pressqto leave.
Check your understanding
stdout (Standard Out)
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.