Javatpoint Logo
Javatpoint Logo

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.

Example

Output

Bash Read File

Reading File Using '$(<fileName>)

Following is the syntax to read the content of the file using '$'

Example

Output

Bash Read File

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:

Command

Output

Bash Read File

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:

Bash Script

Output

Bash Read File

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.

Bash Script

Output

Bash Read File

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.:

Bash Script

Output

Bash Read File

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.


Next TopicBash Write File




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA