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 [OPTIONS] [FILE]
- 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)
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:
What is stdin and stdout?
Read a File to the (Bash) Console (stdout)
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.
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.