Skip to content

Linux Foundations / Find your way around Linux ยท Step 31 of 63

Lesson: stdout (Standard Out)Switch
โ† Linux Foundations

Shell and files

stdout (Standard Out)

Learn where command output goes and how to send it to a file with > and >>.

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
Hello

echo 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
Hello

Nothing 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
Goodbye

1> 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 you

This 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.txt

The 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

  1. Run date > log.txt, then cat log.txt.
  2. Run date >> log.txt twice and count the lines.
  3. Run date > log.txt once more. How many lines remain?
  4. Run ls /etc > listing.txt and read it with less listing.txt. Press q to 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.