Bahs is the most popular shell for Linux distributions and provides different ways and commands to read a file from the command-line interface. Bash can be used to read a file and process it in different ways by using different commands. The file can be a text file or a binary no matter what type is as there are different commands to cope with these file and data types.
Read File with cat Command
The defacto command and way to read a file in Linux bash is using the
cat command. The cat command reads and puts all read content to the standard output which is the current terminal by default.
$ cat numbers.txt
By default, the content is printed to the standard output which is the current terminal. But we can change this by redirecting the file content to another command or file like below.
$ cat numbers.txt > mynumbers.txt
or we can redirect to a command as an input to process them. The pipe operator is used to redirect file content to a command. In the following example, we redirect the file content to the
$ cat numbers.txt | grep 2
Read File with Redirection Operator (<)
Bash provides the redirection operator
< in order to read a file into a command or bash variable. In the following exmaple we read the file
numbers.txt into the variable named
The echo command can be used to read the numbers variable content like below.
$ echo $numbers
Read File Line By Line
The bash provides while loop in order to iterate over lists, arrays, and series. A file can be read as an array that consists of multiple lines by using the while loop. We can read the file line by line by using the redirection operator and process file content line by line.
$ while read line; do echo $line; done < numbers.txt