Bash Read File
There are many ways that we can use to read a file in Bash Shell Scripting. Some of the important methods are given below (Assuming, name of the file that we are reading is ‘read_file.txt’):
Reading File Using ‘cat fileName’
We can use the following syntax to take a print of the contents of the file to a terminal.
Reading File Using ‘$(<fileName>)
Following is the syntax to read the content of the file using ‘$’
Reading File Content from Command-line
If we want to read a file line by line from commands-line without using the ‘cat’ command, we can run the following command to perform a task:
Here, while loop will reach each line of the file and store the content of the line in $line variable which will be printed later.
Reading File Content Using Script
To read the file content using the script, we need to create a bash file and add the following code:
Here, an existing filename is stored in $file variable, and $i variable is used to keep the value of the line number of that line.
Passing filename from Command line and reading the File
Create a bash and add the following script which will pass filename from the command line and read the file line by line. The first argument value is read by the variable $1, which will include the filename for reading. If the file is available in the specified location then while loop will read the file line by line and print the file content.
Here, the filename is used as an argument value. The output will provide the content of ‘read_file.txt’ with no extra spaces between words.
Reading file by omitting Backslash Escape
If we want to read each line of a file line by line by omitting backslash-escape then we are required to use the ‘-r’ option with a ‘read’ command in ‘while’ loop, e.g.:
We may require reading the file for several programming purposes. For example, we can search or match any specific content easily from the file line by line. Hence, it is a useful task for any programming language.