Skip to content

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

Lesson: catSwitch
โ† Linux Foundations

Shell and files

cat

Display, number and join files with cat, and use redirection safely.

cat reads files and writes their contents to standard output, which is normally your screen. The name comes from "concatenate", meaning to join things end to end.

Showing a file

$ cat colors.txt
red
green
blue

cat prints everything at once. That suits short files. For long ones, use less so you can scroll.

Joining files

Give several names and cat prints them one after another, in the order you list them:

$ cat first.txt second.txt
Hello from the first file.
Hello from the second file.

Redirection

The shell can send that output into a file with >:

$ cat first.txt second.txt > both.txt

> creates the file, or erases and replaces it if it already exists. >> adds to the end instead:

$ cat third.txt >> both.txt

Never use a file as both input and output, as in cat a.txt b.txt > a.txt. The shell empties a.txt before cat reads it, so its old contents are lost.

Typing input

With no file name, cat reads what you type. Combined with >, this makes a quick small file:

$ cat > todo.txt
buy milk
call Sam

Press Ctrl+D on an empty line to signal the end of input. Remember that > replaces an existing todo.txt.

Useful options

-n numbers every output line:

$ cat -n colors.txt
     1	red
     2	green
     3	blue

-b numbers only non-blank lines, and -s squeezes repeated blank lines into one. GNU cat also has -A, which makes tabs and line endings visible. Tabs appear as ^I and each line end as $. BSD and macOS cat do not have -A, though -e and -t give similar views.

Practise redirection in the streams and text lab.

Try it

  1. Create two small files with cat > name.
  2. Join them into a third file with >.
  3. Append one of them again with >>.
  4. View the result with cat -n.

Check your understanding

cat

All 5 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.