Shell Script to Read File Brief: This example will help you to read a file in a bash script. This tutorial contains two methods to read a file line by line using a shell script. Method 1 – Using simple loop You can use while read loop to read a file content line by line and store into a variable.
| #!/bin/bash # A shell script to read file line by line filename="/var/log/xyz.log" while read line do # $line variable contains current line read from the file # display $line text on the screen or do something with it. echo "$line" done < $filename |
Note – In above script line is a variable only. You can use any variable name in place of the line of your choice. Method 2 – Using IFS…
Read More Functions in Bash A function which can also be referred to as subroutine or procedure is a block of code used for specific tasks. The function also has a property called re-usability. Bash script also provides functions. Syntax: funcationName(){ // scope of function } functionName //calling of function #1. Bash – Create Function Example Create your first function in shell script showing output “Hello World!”. Create a shell script “script.sh” using following code. #!/bin/bash funHello(){ echo “Hello World!”; } # Call funHello from anywhere in the script like below funHello…
Read More For Loop in Bash In a programming language, a loop is used to repeat the execution of a block of code until the satisfied defined condition. Which is helpful to perform repetitive tasks. Mainly there are 3 types of loops, for, do, and do-while. In this tutorial, we will discuss for loop in shell scripting. The shell scripting also provides for loops to perform repetitive tasks. A basic for loop syntax looks like: Syntax: for VARIABLE in PARAM1 PARAM2 PARAM3 do //for-loop statements done The for loop executes for all…
Read More Command Line Arguments in Shell Script Command line arguments are also known as positional parameters. These arguments are specific with the shell script on terminal during the run time. Each variable passed to a shell script at command line are stored in corresponding shell variables including the shell script name. Synatx: ./myscript.sh ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10 See the below image to understand the command line values and variables. Here ARG1, ARG2 to ARG10 are command line values, which is assigned to corresponding shell variables.…
Read More Shell Scripting The Bash (Born Again) is a Unix shell and command line language written by the Brian Fox. The Born Again shell is used by most of the Unix/Linux operating systems as there default shell. This Shell Script tutorial is written for the peoples want to learn the basics of shell script programming (Shell scripting). In this series of tutorials, you will learn about bash scripting, which is very useful for automating the daily tasks, larger tasks easier. It helps to automation of tasks like backups, disk cleanup etc.
Read More