Home » Linux » Shell » Linux Bash Cat

cat Command in Linux/Bash – How to Use It, With Examples

The cat (concatenate) command in Linux/Bash is most commonly used to read the contents of a file. It outputs the contents of a given file. Here’s how to use it.

cat concatenates files to standard output – by default, this is to the console for viewing on your computer screen. This makes it useful for quickly viewing the contents of files.

It also has other uses, but first, the syntax:

cat Syntax

cat [OPTIONS] [FILE]

Note that:

  • If FILE is not specified, will read from standard input (stdin)
  • Multiple FILEs can be specified, separated by spaces
  • OPTIONS should be a list of options from the below table
  • The command will output data via standard output (stdout)

Options

Here are the commonly used options for cat, straight from the user manual:

-A, –show-all Equivalent to -vET
-b, –number-nonblank Number nonempty output lines, overrides -n
-e Equivalent to -vE
-E, –show-ends Display $ at the end of each line
-n, –number Number all output lines
-s, –squeeze-blank Suppress repeated empty output lines
-t Equivalent to -vT
-T, –show-tabs Display TAB characters as ^I
-v, –show-nonprinting Use ^ and M- notation, except for LFD and TAB

The full user manual can always be viewed by running:

man cat

What is stdin and stdout?

This needs a bit of explaining on its own, but as the cat command is so simple, it’s a good introduction to standard streams. Click here for the full rundown.

Read a File to the (Bash) Console (stdout)

cat text.txt

It’s that easy – cat will read the file and output the contents to the console for you to view.

The contents of the file have been output via stdout, which by default sends the data to the console, but it can also be redirected into another program.

Read File Contents into a Program (via stdin)

cat text.txt | less

As the standard inputs article above outlines, the output from cat can be redirected to the input of other commands.

The command above pipes the contents of text.txt into the less command.

Merging Files

Given the commands namesake, I’d be remiss if I didn’t show you how to use it to merge (concatenate) files:

cat file1 file2  > mergedfile

cat can read from multiple files, so redirecting the output to a single file will result in a file with the contents of all of the read files joined sequentially.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment