Bash Scripting Tutorial ==================================================================================================== Bash Bash Scripting Tutorial provides core and advanced concepts of Bash Shell scripting. Our Bash tutorial is designed for beginners and working professionals. Bash (Bourne Again Shell) is a shell program. It was written by Brian Fox as an enhanced version of the Bourne Shell program 'sh'. It is an open source GNU project. It provides functional improvements over Bourne Shell for both programming and interactive use. Our Bash Shell tutorial includes all the Bash topics such as Bash Scripting, variables, loops, conditional statements, positional parameters, arithmetics, functions, strings, etc. Prerequisite Before learning Bash Shell, you must have the basic knowledge of the Linux Operating System and any programming language. What is Bash? ==================================================================================================== BASH is an acronym for Bourne Again Shell, a punning name, which is a tribute to Bourne Shell (i.e., invented by Steven Bourne). Bash is a shell program written by Brian Fox as an upgraded version of Bourne Shell program 'sh'. It is an open source GNU project. It was released in 1989 as one of the most popular shell distribution of GNU/Linux operating systems. It provides functional improvements over Bourne Shell for both programming and interactive uses. It includes command line editing, key bindings, command history with unlimited size, etc. In basic terms, Bash is a command line interpreter that typically runs in a text window where user can interpret commands to carry out various actions. The combination of these commands as a series within a file is known as a Shell Script. Bash can read and execute the commands from a Shell Script. Bash is the default login shell for most Linux distributions and Apple's mac OS. It is also accessible for Windows 10 with a version and default user shell in Solaris 11. Now have a look at what a Shell is known for. Shell: A UNIX Shell is a program or a command line interpreter that interprets the user commands which are either entered by the user directly or which can be read from a file (i.e., Shall Script), and then pass them to the operating system for processing. It is important to note that Shall scripts are interpreted and not compiled, as the computer system interprets them and there is not any need to compile Shell Scripts in order of execution. There are different types of shells available in Linux Operating Systems. Some of which are as follows: 1. Bourne Shell 2. C shell 3. Korn Shell 4. GNU Bourne Shell To know, which shell types your operating system supports, type the command into the terminal as given below: cat /etc/shells And to know where bash is located in your OS, type the below command and you will get a specific location: which bash History of Bash ==================================================================================================== * Previously, most of the software in the UNIX world was proprietary and closed source. UNIX system was also not open-sourced for which, you had to use a shell. There was a shell existed at that time named by "Bourne Shell" under the /bin/sh command which was proprietary and closed source. Bourne named after its inventor- Steven Bourne. * Richard Stallman at that time began GNU project with Free Software Foundation (FSF) to create a UNIX-compatible operating system aiming everything as open-source. There was a lack of progress in the revolution. He needed a free shell that could run existing shell scripts. It was imperative to a completely open-source system built as one of the few projects he funded with FSF. Then on January 110, 1988, Brian Fox (FSF employee) began coding on Bash and released Bash as beta, version 0.99 on June 8, 1989. * Brian Fox remained in FSF as the primary Bash maintainer till 1993. Then he laid off from FSF, and Chet Ramey (earlier contributor in FSF) got his responsibility. * Further, on December 23, 1996, Chet Ramey released another bash version 2.0 for the public with a range of new features over the old bash version. * And now Chet Ramey is known for the official bash maintainer, and he continues to make further enhancements in bash. Bash is the standard shell included with Linux. It is the most popular shell known today of being open-source and also with various productive features we read in the further topic. It is available for Linux distributions, macOS, Solaris 11, and Windows 10 too. It is offering the best experience for its users with a lot of improvements. Features of Bash ==================================================================================================== 1. Bash is sh-compatible as it derived from the original UNIX Bourne Shell. It is incorporated with the best and useful features of the Korn and C shell like directory manipulation, job control, aliases, etc. 2. Bash can be invoked by single-character command line options (-a, -b, -c, -i, -l, -r, etc. ) as well as by multi-character command line options also like --debugger, --help, --login, etc. 3. Bash Start-up files are the scripts that Bash reads and executes when it starts. Each file has its specific use, and the collection of these files is used to help create an environment. 4. Bash consists of Key bindings by which one can set up customized editing key sequences. 5. Bash contains one-dimensional arrays using which you can easily reference and manipulate the lists of data. 6. Bash comprised of Control Structures like the select construct that specially used for menu generation. 7. Directory Stack in Bash specifies the history of recently-visited directories within a list. Example: pushd builtin is used to add the directory to the stack, popd is to remove directory from the stack and dirs builtin is to display content of the directory stack. 8. Bash also comprised of restricted mode for the environment security. A shell gets restricted if bash starts with name rbash, or the bash --restricted, or bash -r option passed at invocation. ______________________________________________________________________________________________________________________________________________________________________ Bash Scripting ==================================================================================================== Bash Scripting is a powerful part of system administration and development used at an extreme level. It is used by the System Administrators, Network Engineers, Developers, Scientists, and everyone who use Linux/Unix operating system. They use Bash for system administration, data crunching, web application deployment, automated backups, creating custom scripts for various pages, etc. Script In Computer programming, a script is a set of commands for an appropriate run time environment which is used to automate the execution of tasks. Bash Script: A Bash Shell Script is a plain text file containing a set of various commands that we usually type in the command line. It is used to automate repetitive tasks on Linux filesystem. It might include a set of commands, or a single command, or it might contain the hallmarks of imperative programming like loops, functions, conditional constructs, etc. Effectively, a Bash script is a computer program written in the Bash programming language. How to create and run a Bash Script? * To create an empty bash script, first, change the directory in which you want to save your script using cd command. Try to use text editor like gedit in which you want to type the shell commands. * Use touch command to create the zero bytes sized script. touch file_name Here, .sh is suffixed as an extension that you have to provide for execution. * Type the shell commands for your bash script in the newly opened text window or the text editor. Before typing bash shell commands, first, look at the base of any bash script. Each Bash based Linux script starts by the line- #! /bin/bash Where #! is referred to as the shebang and rest of the line is the path to the interpreter specifying the location of bash shell in our operating system. Bash use # to comment any line. Bash use echo command to print the output. At the end, execute the bash script prefixing with ./. Have a look at the basic terms of a Bash Script, i.e., SheBang and echo command. SheBang (#!) The She Bang (#!) is a character sequence consisting of the characters number sign (#) and exclamation mark (!) at the beginning of a script. Under the Unix-like operating systems, when a script with a shebang runs as a program, the program loader parses the rest of the lines with the first line as an interpreter directive. So, SheBang denotes an interpreter to execute the script lines, and it is known as the path directive for the execution of different kinds of Scripts like Bash, Python, etc. Here is the correct SheBang format for the discussed Bash Script. #!/bin/bash The formatting for shebang is most important. Its incorrect format can cause improper working of commands. So, always remember these two points of SheBang formatting while creating a Script as follows: 1. It should always be on the very first line of the Script. 2. There should not be any space before the hash (#), between the hash exclamation marks (#!), and the path to the interpreter. echo echo is a built-in command in Bash, which is used to display the standard output by passing the arguments. It is the most widely used command for printing the lines of text/String to the screen. Its performance is the same on both the platforms: Bash Shell and Command Line Terminal. Syntax: echo [option] [string] echo [string] NOTE: If you want to print space between any two lines of your Script. Then type echo as given below: echo Filesystem and File Permissions ==================================================================================================== The Filesystem is a kind of structure organized with the collection of files or folders. It determines control over data, i.e., how data is to be stored and retrieved? Linux Filesystem is a tree-like structure comprised of lots of directories. These directories are just the files containing the list of other files. Linux makes no difference between the files and directories. All the files in Linux filesystem are known as directories, and these files are categorized as follows: 1. Ordinary files that contain data, text, images, program instructions. 2. Special files that give access to hardware devices. 3. Directories that contain both the ordinary and special files. Let's have a look on Linux filesystem. List all the files and directories by using ls -l command. Filesystem and File Permissions There are seven columns in the given image, which are defined as follows: * The first column represents the file type and file permissions. Every file row begins with the file type and then specifies the access permissions associated with the files. These are the following types of files with their specific characters: 1. Regular file (-) 2. Directory (d) 3. Link (l) 4. Special File (c) 5. Socket (s) 6. Named pipe (p) 7. Block device (b) * The second column represents the number of memory blocks. * The third column represents the owner of the file or the superuser, who has the administrating power. * The fourth column represents the group of owner/superuser. * The fifth column represents the file size. * The sixth column represents the date and time when the file was created or lastly modified. * The last column represents the name of the file or the directory. File Permissions In spite of having the best security features, Linux-based Operating System requires file permissions to secure its filesystem, as there are file permission based issues that occur when a user assigns improper permissions to the files and directories. These issues may cause malicious or accidental tampering to the filesystem. So Linux secures its filesystem with two authorization attributes as follows: 1. Permissions There are three types of permissions associated with the files as follows: Read (r) permission by which you can view the content of the file. Write (w) permission by which you can modify the file content. Execute (x) permission by which one can run the programming file or script. Note: Dash (-) is provided in case of permission get invoked. 2. Ownership There are three types of Linux users as follows: Owner is the superuser who creates the file. He can access all the permissions associated with a file that includes reading, modifying, and running the file. Group is known as a set of users or multi-users. The superuser creates it. Every member in a group has the same access permissions associated with a file. Other users, i.e., the third-party users can be anybody else who doesn't belong to the Superuser/Group members. They use the permissions associated with any file or directory which are created or owned by the Superuser/Group members. Let's understand this concept by the given an example. Filesystem and File Permissions See the first column of the darkened row. It has ten slots. * The first one slot (-) represents a file named by aa.sh * Next three slots (rw-) specify the permissions used by the assigned owner. These permissions include read and write. Here, execute permission is denied. * Next three slots (rw-) specify the permissions used by the group members who own the directory. These permissions include read and write, but do not include execute permission. * Next three slots (r--) specify the permissions used by the third=party users. These permissions include read permission only. Here, read and write both the permissions have been denied. Changing Permissions You can alter the file permissions for each class (user/group/others) by using chmod command. The basic form to remove or add any permission for any class is: chmod [class][operator][permission] file_name chmod [ugoa][+or-][rwx] file_name where class is represented by the indicators - u, g, o, and a such that u for the user, g for the group, o for the other, and a for all the classes. operator ( + or - ) is used to add or remove the permission. permission is represented by the indicators r, w, x to allow access for reading, modifying, or running the script respectively. Let we alter the permissions of darkened aa.sh file given below: Filesystem and File Permissions 1. Add the denied permissions for all classes. Filesystem and File Permissions 2. Remove the write and execute permission for other class. Filesystem and File Permissions And so you can alter any permission for any class if you find any need. Hello World! Bash Script ==================================================================================================== As per the discussion in previous topics, let's move to create a first and basic Bash Script by using the given steps: Step 1: Open the terminal. Navigate the desktop folder or directory using the cd command. Step 2: Create an empty file as a shell script using touch command and name it as bash_script.sh to execute. In the below image, you can see the created file with all the permission attributes in the darkened row. Hello World! Bash Script Step 3: Open the file using any editor or visual studio. For using editor gedit, type gedit bash_script.sh/ Step 4:Now Code for the intended script, i.e., Hello World! #! /bin/bash # This is the basic bash script echo " Hello World! " Where, Line 1 represents #! (shebang) and specifies the bash shell location. Line 2 represents the commented line. Line 3 represents echo command to print the output. Step 5:Execute the Script prefixing with ./. Hello World! Bash Script It will throw the Permission denied error. Because the file has only read and write permissions but not execute permission, you can see it below: Hello World! Bash Script So we add the execute permission to the file using chmodcommand with +x option as chmod +x bash_script.sh and finally, execute the script. Hello World! Bash Script Relative vs. Absolute path ==================================================================================================== Before creating a first Bash Script, you should be well aware of the shell navigation and the difference between the relative and absolute path for an intended file. So let's understand what they are? What is the Path? A path to a file is a merged form of slash (/) and alpha-numeric characters. It determines the unique location of a file or directory in an OS filesystem. Absolute Path An Absolute Path is a full path specifying the location of a file or directory from the root directory or start of the actual filesystem. Example: /home/javatpoint/Desktop/CollegeStudent * An Absolute path of any directory always starts with a slash (/) representing the directory root. Besides this, all slashes in the directory path separate the directories. * All directories names in the absolute path are written in the hierarchy order. The parent directory name is written on the left side. * The last name in an absolute path may belong to a file or directory. Besides the last name, all names belong to the directories. * The absolute path of the current directory can be determined by using the pwd command. Relative Path The relative path of a file is its location relative to the current working directory. It never starts with a slash (/). It begins with the ongoing work directory. Example: Desktop/CollegeStudent * Single Dot (.) resolves to the current directory. * Double Dot (..) resolves to the parent directory of the present work directory. * Tilde (~) represents the home directory of logged in user. Relative Path Vs Absolute Path: The topmost directory in any filesystem is the root directory denoted by the slash (/). You can describe the location of any file or directory in the filesystem with the absolute path. That means you will take every step starting from the root directory or the absolute beginning of the filesystem. An absolute path is unambiguous and may be inconvenient to work with, especially if you are working with deeply nested directories. To get a simpler mode of the things, you can use the Relative path instead. Such that, if you are working with files in or near the present working directory, this can save you from a lot of typing. Every time you've referred to a file by just its name, you've been using a relative path. This is the most straightforward sort of relative path. The shell looks for the specified file name within the current directory. Shell Navigation: There are two commands (cd and pwd) which help in the navigation of GNU/Linux filesystem thoroughly, where, 1. cd is used for changing the directory, 2. pwd for printing the current working directory. Bash Comments ==================================================================================================== In this topic, we will understand how to insert comments in a Bash Script file. Comments are the necessary part of any programming language. They are used to define the usage of any code or function. Comments are the strings which help in the readability of a program. They are not executed when we execute the commands in Bash Script file. Bash script provides support for two types of comments, just like the other programming language. * Single Line Comment * Multiple/ Multi-Line Comment Bash Single Line Comment To write single line comment in bash, we have to use hash (#) symbol at the starting of the comment. Following is an example of Bash Script which contains single-line comments in between commands: #!/bin/bash #This is a single-line comment in Bash Script. echo "Enter your name:" read $name echo #echo output, its also a single line comment echo "The current user name is $name" #This is another single line comment Here, it can be clearly seen that comments are ignored while the execution of the commands is in process. Bash Multi Line Comment There are two ways to insert multi-line comments in bash scripts: * We can write multi-line comments in bash scripting by enclosing the comments between < Follow the given examples to read user input from the Bash Script: Example 1: In this example, we read both the single and multiple variables from the Bash Script by using read command. Program: #!/bin/bash # Read the user input echo "Enter the user name: " read first_name echo "The Current User Name is $first_name" echo echo "Enter other users'names: " read name1 name2 name3 echo "$name1, $name2, $name3 are the other users." What will happen if we don't pass any variable with the read command? If we don't pass any variable with the read command, then we can pass a built-in variable called REPLY (should be prefixed with the $ sign) while displaying the input. It can be explained using the below program: Program: #!/bin/bash # using read command without any variable echo "Enter name : " read echo "Name : $REPLY" Example 2: In this example, we enter the input on the same PROMPT by using the -p command line option as follows: read -p PROMPT Program: #!/bin/bash read -p "username:" user_var echo "The username is: " $user_var Example 3: This example is to keep the input on silent mode, such that whatever be a user input on the command line will be hidden to others. So, we pass a username and hide the password (silent mode) by using the command line options (-s, -p) commonly as follows: read -sp PROMPT Where -s allows a user to keep the input on silent mode and -p to input on newly command prompt. Program: #!/bin/bash read -p "username : " user_var read -sp "password : " pass_var echo echo "username : " $user_var echo "password : " $pass_var NOTE: At the 5^th line of the script, we have given a blanked line with echo command, because if we do not make it blank then, it will give output with both the password and username on the same PROMPT as the below image. So, write your script by adding a blank echo command line. Example 4: This example is to enter multiple inputs using an array. So use the -a command line option as follows: read -a Where -a helps script to read an array, and variable_name refers to an array. Program: #!/bin/bash # Reading multiple inputs using an array echo "Enter names : " read -a names echo "The entered names are : ${names[0]}, ${names[1]}. Bash Date Formatting ==================================================================================================== In this topic, we will learn about available format options for date command and understand how can we use them with Bash Scripts. Bash Date Bash shell provides different date commands along with different formatting options. We can use those commands to format Bash date to a required one. Bash Date Command We can use the `date` command to display or change the current date and time value of the system. We can print date and time value in different formats by using date command. We can also use this command for calculating date and time value-related tasks. If `date` command is used without any option, then it will print the current system's date and time value. This command contains several formatting options to format the output. The syntax of date command is given below: $ date Format Bash Date with Options As we have discussed above, we can format the Bash Date. We can also use spaces with the format that you are going to use. Date command accepts the options if provided like: $ date + If we want to format the date with spaces, we can use the syntax: $ date '+ List of Bash Date Formatting-options There are different types of formatting codes or characters available, which can be used with the date options to generate the formatted output. Following is a list of some common options and format codes for date command: Options: -d or -date= String It is used to display the time set by the String value. -s, -set=String It is used to set the time set by the String value. -f or -file=DateFile It is used to process multiple dates. -I or -iso-8601[=Timespec] It is used to generate an ISO 8601 compliant date/time string output. -r or -reference=File It is used to print the last modification time of a file. -u, -utc, -universal It is used to print or set Coordinated Universal Time. -help It is used for getting the help of this command. -version It is used to get the version information. Format Option Codes Format Option with Codes Part of Date Description Example Output date +%a Weekday Name of a weekday in short form (e.g., Sun, Mon, Tue, Wed, Thu, Fri, Sat Mon date +%A Weekday Name of the weekday in full form (e.g., Sunday, Monday, Tuesday, etc.) Monday date +%b Month Name of the month in short form (e.g., Jan, Feb, Mar, etc.) Jan date +%B Month Name of the month in full form (e.g., January, February, etc.) January date +%d Day Day of the month (e.g., 01) 27 date +%D MM/DD/YY Current Date; shown in MM/DD/YY 08/27/2019 date +%F YYYY-MM-DD Date; shown in YYYY-MM-DD 2019-08-27 date +%H Hour Hour in 24-hour clock format 16 date +%I Hour Hour in 12-hour clock format 04 date +%j Day Day of year (e.g., 001 to 366) 239 date +%m Month Number of month (01 to 12 where 01 is January) 08 date +%M Minutes Minutes (00 to 59) 55 date +%S Seconds Seconds (00 to 59) 28 date +%N Nanoseconds Nanoseconds (000000000 to 999999999) 300261496 date +%T HH:MM:SS Time as HH:MM:SS (Hours in 24 Format) 15:59:10 date +%u Day of Week Day of week (01 to 07 where 01 is Monday) 02 date +%U Week Displays week number of year where Sunday is the first day of the week (00 to 53) 35 date +%Y Year Displays full year (i.e., YYYY) 2019 date +%Z Timezone Time zone abbreviation (e.g., IST, GMT) GMT We can use any of the formats as mentioned above (first column) for the date command as per requirement. Examples Bash Date Format MM-DD-YYYY To use the date in MM-DD-YYYY format, we can use the command date +%m-%d-%Y. Bash Script Program #!/bin/bash d=`date +%m-%d-%Y` echo "Date in format MM-DD-YYYY" echo $d #MM-DD-YYYY It is very important to note that format option codes are case sensitive. In this example, we have used %m for a month, %d for a day and %Y for a year. If we had used %M in place of %m, then it would define minutes. Bash Date Format MM-YYYY To use the date in MM-YYYY format, we can use the command date +%m-%Y. Bash Script Program #!/bin/bash d=`date +%m-%Y` echo "Date in format MM-YYYY" echo $d # MM-YYYY Bash Date Format Weekday DD-Month-YYYY To use the date in Weekday DD-Month, YYYY format, we can use the command date +%A %d-%B, %Y. Bash Script Program #!/bin/bash d=`date '+%A %d-%B, %Y'` echo "Date in format Weekday DD-Month, YYYY" echo $d # Weekday DD-Month, YYYY Bash Sleep ==================================================================================================== In this topic, you will understand how to use sleep command by using different bash scripts. Sleep is a command-line utility which allows us to suspend the calling process for a specified time. In other words, Bash sleep command is used to insert a delay or pause the execution for a specified period of time. When the programmer needs to pause the execution of any command for the specific purpose, then this command can be used with the specific time value. One can set the delay amount by seconds (s), minutes (m), hours (h), and days (d). This command is especially useful when it is used within a bash shell script. Sleep Command Syntax Following is the syntax for the sleep command in Bash: sleep number[suffix] You can use any positive integer or fractional number as time value. A suffix is an optional part. You can apply any of the following as suffix: * s - seconds * m - minutes * h - hours * d - days Note: When there is no suffix, then the number is considered to be in seconds (by default). When two or more arguments are specified, then the total amount of time will be considered as the time equivalent to the sum of their values. Following are the few simple examples showing how to use sleep command: * Sleep for 9 seconds, use sleep 9 or sleep 9s * Sleep for 0.5 seconds, use sleep 0.5 or sleep 0.5s * Sleep for 2 minute and 30 seconds, use sleep 2m 30s * Sleep for 8 hours sleep 8h * Sleep for 2 days, 9 hours, 5 minute and 55 seconds, use sleep 2d 9h 5m 55s Bash Scripts Example We are going to explain the most basic example of sleep command in Bash. Bash Script #!/bin/bash # start time date +"%H:%M:%S" echo "wait for 9 seconds" # sleep for 9 seconds sleep 9s # you can also use "sleep 9" in place of "sleep 9s" bec # end time date +"%H:%M:%S" echo "Task Completed" How the script works When we run the script, it will print the current time in HH:MM:SS format. Then the echo command will execute and print the message "wait for 9 seconds". Then the sleep command will execute and pause the script for 9 seconds. When the specified time period elapses, the next line of the script will again print the current time. Lastly, the echo command will print the message "Task Completed". Similarly, you can run sleep command for minutes, hours, and days. Bash Arithmetic Operators ==================================================================================================== In this topic, we will understand how to use arithmetic operators in Bash. Depending on what type of result we want through our scripts, we may need to apply arithmetic operators at some point. Like variables, they are reasonably easy to apply. In the bash script, we can perform arithmetic operations on numeric values to get the desired result. There are 11 arithmetic operators which are supported by Bash Shell. Look at the following table demonstrating the syntax, description and examples for each of the arithmetic operators: Operator Description Examples + Addition, measures addition of numbers (operands) $(( 10 + 3 )), result=13 - Substraction, measures subtraction of second operand from first $(( 10 - 3 )), result=7 * Multiplication, measures the multiplication of operands. $(( 10 * 3 )), result=30 / Division, measures the division of first operand by second operand and and return quotient. $(( 10 / 3 )), result=3 ** Exponentiation, measures the result of second operand raised to the power of first operand. $(( 10 ** 3 )), result=1000 % Modulo, measures remainder when the first operand is divided by second operand. $(( 10 % 3 )), result=1 += Increment Variable by Constant- used to increment the value of first operand by the constant provided. x=10 let "x += 3" echo $x result=13 -= Decrement Variable by Constant- used to decrement the value of first operand by the constant provided. x=10 let "x -= 3" echo $x result=7 *= Multiply Variable by Constant- used to multiply the value of the first operand by the constant provided. x=10 let "x *= 3" echo $x result=30 /= Divide Variable by Constant- used to calculate the value of (variable / constant) and store the result back to variable. x=10 let "10 /= 3" echo $x result=3 %= Remainder of Dividing Variable by Constant- used to calculate the value of (variable % constant) and store the result back to variable. x=10 let "10 %= 3" echo $x result=1 Performing Arithmetic Operations in Bash There are many options to perform arithmetic operations on the bash shell. Some of the options are given below that we can adopt to perform arithmetic operations: Double Parentheses Double parentheses is the easiest mechanism to perform basic arithmetic operations in the Bash shell. We can use this method by using double brackets with or without a leading $. Syntax ((expression)) We can apply four different ways to achieve the required objectives. Look at the methods given below to understand how the double parentheses mechanism can be used (Assuming that we want to add the numbers 10 and 3) : Method 1 Sum=$((10+3)) echo "Sum = $Sum" Method 2 ((Sum=10+3)) echo "Sum = $Sum" Method 3 Num1=10 Num2=3 ((Sum=Num1+Num2)) echo "Sum = $Sum" Method 4 Num1=10 Num2=3 Sum=$((Num1+Num2)) echo "Sum = $Sum" All of these methods will provide the same output as: Sum = 13 Following is an example demonstrating the use of double parentheses for arithmetic operations in a Bash shell script: Bash Script #!/bin/bash x=8 y=2 echo "x=8, y=2" echo "Addition of x & y" echo $(( $x + $y )) echo "Subtraction of x & y" echo $(( $x - $y )) echo "Multiplication of x & y" echo $(( $x * $y )) echo "Division of x by y" echo $(( $x / $y )) echo "Exponentiation of x,y" echo $(( $x ** $y )) echo "Modular Division of x,y" echo $(( $x % $y )) echo "Incrementing x by 5, then x= " (( x += 5 )) echo $x echo "Decrementing x by 5, then x= " (( x -= 5 )) echo $x echo "Multiply of x by 5, then x=" (( x *= 5 )) echo $x echo "Dividing x by 5, x= " (( x /= 5 )) echo $x echo "Remainder of Dividing x by 5, x=" (( x %= 5 )) echo $x Let Construction Let is a built-in command of Bash that allows us to perform arithmetic operations. It follows the basic format: Syntax let An example is given below explaining how to use let command in a Bash script: Bash script #!/bin/bash x=10 y=6 z=0 echo "Addition" let "z = $(( x + y ))" echo "z= $z" echo "Substraction" let "z = $((x - y ))" echo "z= $z" echo "Multiplication" let "z = $(( x * y ))" echo "z = $z" echo "Division" let "z = $(( x / y ))" echo "z = $z" echo "Exponentiation" let "z = $(( x ** y ))" echo "z = $z" echo "Modular Division" let "z = $(( x % y ))" echo "z = $z" let "x += 5" echo "Incrementing x by 5, then x= " echo $x let "x -= 5" echo "Decrementing x by 5, then x= " echo $x let "x *=5" echo "Multiply of x by 5, then x=" echo $x let "x /= 5" echo "Dividing x by 5, x= " echo $x let "x %= 5" echo "Remainder of Dividing x by 5, x=" echo $x Backticks In bash scripting, an arithmetic expansion can also be performed using backticks and expr (known as all-purpose expression evaluator). The `expr` is similar to 'let,' but it does not save the result to a variable. It directly prints the result. Unlike let, we don't need to enclose the expression within the quotes. We are required to use spaces between the items of the expression. It is important to note that we should use 'expr` within command substitution to save the output to a variable. We can also use `expr` without 'backticks'. Syntax `expr item1 operator item2` or expr item1 operator item2 An example is given below explaining how to use backticks and expr in a Bash script: Bash Script Program #!/bin/bash #Basic arithmetic using expr echo "a=10, b=3" echo "c is the value of addition c=a+b" a=10 b=3 echo "c= `expr $a + $b`" Bash If ==================================================================================================== In this topic, we will understand how to use if statements in Bash scripts to get our automated tasks completed. Bash if statements are beneficial. They are used to perform conditional tasks in the sequential flow of execution of statements. If statements usually allow us to make decisions in our Bash scripts. They help us to decide whether or not to run a piece of codes based upon the condition that we may set. Basic if Statements A basic if statement commands that if a particular condition is true, then only execute a given set of actions. If it is not true, then do not execute those actions. If statement is based on the following format: Syntax if [ expression ];_____________________________________ then___________________________________________________ statements_____________________________________________ fi_____________________________________________________ The statement between then and fi (If backwards) will be executed only if the expression (between the square brackets) is true. Note: Observe the spaces used in the first line and a semicolon at the end of the first line; both are mandatory to use. If conditional statement ends with fi. * For using multiple conditions with AND operator: if [ expression_1 ] && [ expression_2 ];_______________ then___________________________________________________ statements_____________________________________________ fi_____________________________________________________ * For using multiple conditions with OR operator: if [ expression_1 ] || [ expression_2 ];_______________ then___________________________________________________ statements_____________________________________________ fi_____________________________________________________ * For compound expressions with AND & OR operators, we can use the following syntax: if [ expression_1 && expression_2 || expression_3 ];___ then___________________________________________________ statements_____________________________________________ fi_____________________________________________________ Following are some examples demonstrating the usage of if statement: Example 1 In this example, take a user-input of any number and check if the value is greater than 125. #!/bin/bash____________________________________________ _______________________________________________________ read -p " Enter number : " number______________________ _______________________________________________________ if [ $number -gt 125 ]______________________________________ then________________________________________________________ echo "Value is greater than 125"____________________________ fi__________________________________________________________ Example 2 In this example, we demonstrate the usage of if statement with a simple scenario of comparing two strings: #!/bin/bash____________________________________________ _______________________________________________________ # if condition is true_________________________________ if [ "myfile" == "myfile" ];___________________________ then________________________________________________________ echo "true condition"_______________________________________ fi__________________________________________________________ ____________________________________________________________ # if condition is false_____________________________________ if [ "myfile" == "yourfile" ];______________________________ then________________________________________________________ echo "false condition"______________________________________ fi__________________________________________________________ Example 3 In this example, we demonstrate how to compare numbers by using the if statement: #!/bin/bash____________________________________________ _______________________________________________________ #if condition (greater than) is true___________________ if [ 10 -gt 3 ];_______________________________________ then________________________________________________________ echo "10 is greater than 3."________________________________ fi__________________________________________________________ ____________________________________________________________ #if condition (greater than) is false_______________________ if [ 3 -gt 10 ];____________________________________________ then________________________________________________________ echo "3 is not greater than 10."____________________________ fi__________________________________________________________ ____________________________________________________________ #if condition (lesser than) is true_________________________ if [ 3 -lt 10 ];____________________________________________ then________________________________________________________ echo "3 is less than 10."___________________________________ fi__________________________________________________________ ____________________________________________________________ #if condition (lesser than) is false________________________ if [ 10 -lt 3 ];____________________________________________ then________________________________________________________ echo "10 is not less than 3."_______________________________ fi__________________________________________________________ ____________________________________________________________ #if condition (equal to) is true____________________________ if [ 10 -eq 10 ];___________________________________________ then________________________________________________________ echo "10 is equal to 10."___________________________________ fi__________________________________________________________ ____________________________________________________________ #if condition (equal to) is false___________________________ if [ 10 -eq 9 ];____________________________________________ then________________________________________________________ echo "10 is not equal to 9"_________________________________ fi__________________________________________________________ Example 4 In this example, we will define how to use AND operator to include multiple conditions in the if expression: #!/bin/bash____________________________________________ _______________________________________________________ # TRUE && TRUE_________________________________________ if [ 8 -gt 6 ] && [ 10 -eq 10 ];_______________________ then________________________________________________________ echo "Conditions are true"__________________________________ fi__________________________________________________________ ____________________________________________________________ # TRUE && FALSE_____________________________________________ if [ "mylife" == "mylife" ] && [ 3 -gt 10 ];________________ then________________________________________________________ echo "Conditions are false"_________________________________ fi__________________________________________________________ Example 5 In this example, we will define how to use OR operator to include multiple conditions in the if expression: #!/bin/bash____________________________________________ _______________________________________________________ # TRUE || FALSE________________________________________ if [ 8 -gt 7 ] || [ 10 -eq 3 ];________________________ then _______________________________________________________ echo " Condition is true. "_________________________________ fi__________________________________________________________ ____________________________________________________________ # FALSE || FALSE____________________________________________ if [ "mylife" == "yourlife" ] || [ 3 -gt 10 ];______________ then________________________________________________________ echo " Condition is false. "________________________________ fi__________________________________________________________ Example 6 In this example, we will define how to use AND and OR to include multiple conditions in the if expression: #!/bin/bash____________________________________________ _______________________________________________________ # TRUE && FALSE || FALSE || TRUE_______________________ if [[ 10 -eq 10 && 5 -gt 4 || 3 -eq 4 || 3 -lt 6 ]];___ then________________________________________________________ echo "Condition is true."___________________________________ fi__________________________________________________________ ____________________________________________________________ # TRUE && FALSE || FALSE____________________________________ if [[ 8 -eq 8 && 8 -gt 10 || 9 -lt 5 ]];____________________ then________________________________________________________ echo "Condition is false"___________________________________ fi__________________________________________________________ Options for If statement in Bash Scripting If statement contains many options to perform a specific task. These options can be used for file operations, string operations, etc. Following are the some mostly used options: - Options (Operators) Description ! EXPRESSION To check if EXPRESSION is false. -n STRING To check if the length of STRING is greater than zero. -z STRING To check if the length of STRING is zero (i.e., it is empty) STRING1 == STRING2 To check if STRING1 is equal to STRING2. STRING1 != STRING2 To check if STRING1 is not equal to STRING2. INTEGER1 -eq INTEGER2 To check if INTEGER1 is numerically equal to INTEGER2. INTEGER1 -gt INTEGER2 To check if INTEGER1 is numerically greater than INTEGER2. INTEGER1 -lt INTEGER2 To check if INTEGER1 is numerically less than INTEGER2. -d FILE To check if FILE exists and it is a directory. -e FILE To check if FILE exists. -r FILE To check if FILE exists and the read permission is granted. -s FILE To check if FILE exists and its size is greater than zero (which means that it is not empty). -w FILE To check if FILE exists and the write permission is granted. x FILE To check if FILE exists and the execute permission is granted. Nested If You can apply as many 'if statements' as required inside your bash script. It is also possible to use an if statement inside another 'if statement'. It is known as Nested If Statement. Example In this example, we will find "if a given number is greater than 50 and if it is an even number" by using nested if expression. #!/bin/bash____________________________________________ #Nested if statement___________________________________ _______________________________________________________ if [ $1 -gt 50 ]_______________________________________ then________________________________________________________ echo "Number is greater than 50."_________________________ ____________________________________________________________ if (( $1 % 2 == 0 ))______________________________________ then______________________________________________________ echo "and it is an even number."________________________ fi________________________________________________________ fi__________________________________________________________ Bash If Else ==================================================================================================== In this topic, we will understand how to use if-else statements in Bash scripts to get our automated tasks completed. Bash if-else statements are used to perform conditional tasks in the sequential flow of execution of statements. Sometimes, we want to process a specific set of statements if a condition is true, and another set of statements if it is false. To perform such type of actions, we can apply the if-else mechanism. We can apply the condition with the 'if statement'. Bash If Else Syntax A syntax of if-else statement in Bash Shell Scripting can be defined as below: if [ condition ];______________________________________ then___________________________________________________ _________________________________ else___________________________________________________ _____________________________________ fi__________________________________________________________ Important Points to Remember * We can use a set of one or more conditions joined using conditional operators. * Else block commands includes a set of actions to perform when the condition is false. * The semi-colon (;) after the conditional expression is a must. Check out the following examples demonstrating the use of the if-else statement in Bash Script: Example 1 Following example consists of two different scenarios where in the first if-else statement, the condition is true, and in the second if-else statement, the condition is false. #!/bin/bash____________________________________________ _______________________________________________________ #when the condition is true____________________________ if [ 10 -gt 3 ];_______________________________________ then________________________________________________________ echo "10 is greater than 3."______________________________ else________________________________________________________ echo "10 is not greater than 3."__________________________ fi__________________________________________________________ ____________________________________________________________ #when the condition is false________________________________ if [ 3 -gt 10 ];____________________________________________ then________________________________________________________ echo "3 is greater than 10."______________________________ else________________________________________________________ echo "3 is not greater than 10."__________________________ fi__________________________________________________________ In the first if-else expression, the condition ( 10 -gt 3 ) is true and so the statement in the if block is executed. Whereas in the other if-else expression, the condition ( 3 -gt 10 ) is false and so the statement in the else block is executed. Example 2 In this example, we explained how to use multiple conditions with the if-else statement in Bash. We use bash logical operators to join multiple conditions. #!/bin/bash____________________________________________ _______________________________________________________ # When condition is true_______________________________ # TRUE && FALSE || FALSE || TRUE_______________________ if [[ 10 -gt 9 && 10 == 9 || 2 -lt 1 || 25 -gt 20 ]];_______ then________________________________________________________ echo "Given condition is true."___________________________ else________________________________________________________ echo "Given condition is false."__________________________ fi__________________________________________________________ ____________________________________________________________ # When condition is false___________________________________ #TRUE && FALSE || FALSE || TRUE_____________________________ if [[ 10 -gt 9 && 10 == 8 || 3 -gt 4 || 8 -gt 8 ]];_________ then________________________________________________________ echo "Given condition is true."___________________________ else________________________________________________________ echo "Given condition is not true."_______________________ fi__________________________________________________________ Bash If Else Statement in a Single Line We can write complete 'if-else statement' along with the commands in a single line. You need to follow the given rules to use if-else statement in a single line: * Use a semi-colon (;) at the end of statements in if and else blocks. * Use spaces as a delimiter to append all the statements. An example is given below demonstrating how to use if-else statement in a single line: Example #!/bin/bash____________________________________________ _______________________________________________________ read -p "Enter a value:" value_________________________ if [ $value -gt 9 ]; then echo "The value you typed is Bash Nested If Else Just like nested if statement, the if-else statement can also be used inside another if-else statement. It is called nested if-else in Bash scripting. Following is an example explaining how to make use of the nested if-else statement in Bash: Example #!/bin/bash____________________________________________ _______________________________________________________ read -p "Enter a value:" value_________________________ if [ $value -gt 9 ];___________________________________ then________________________________________________________ if [ $value -lt 11 ];_____________________________________ then______________________________________________________ echo "$value>9, $value<11"_____________________________ else______________________________________________________ echo "The value you typed is greater than 9."___________ fi________________________________________________________ else echo "The value you typed is not greater than 9."______ fi__________________________________________________________ Bash Else If ==================================================================================================== In this topic, we will understand how to use else-if (elif) statements in Bash scripts to get our automated tasks completed. Bash else-if statement is used for multiple conditions. It is just like an addition to Bash if-else statement. In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked. Syntax of Bash Else If (elif) The syntax of else-if statement in Bash shell scripting can be defined as: if [ condition ];______________________________________ then___________________________________________________ _____________________________________________ elif [ condition ];____________________________________ then________________________________________________________ __________________________________________________ else________________________________________________________ __________________________________________________ fi__________________________________________________________ Just like if-else, we can use a set of one or more conditions joined using conditional operators. The set of commands are executed when the condition is true. If there is no true condition, then the block of commands inside the 'else statement' is executed. Following are some examples demonstrating the usage of the else-if statement: Example 1 Following example consists of two different scenarios wherein the first else-if statement, the condition is true, and in the second else-if statement, the condition is false. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ read -p "Enter a number of quantity:" num______________ _______________________________________________________ if [ $num -gt 100 ];________________________________________ then________________________________________________________ echo "Eligible for 10% discount"____________________________ elif [ $num -lt 100 ];______________________________________ then________________________________________________________ echo "Eligible for 5% discount"_____________________________ else________________________________________________________ echo "Lucky Draw Winner"____________________________________ echo "Eligible to get the item for free"____________________ fi__________________________________________________________ Example 2 This example is demonstrating how to use multiple conditions with the else-if statement in Bash. We use bash logical operators to join multiple conditions. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ read -p "Enter a number of quantity:" num______________ _______________________________________________________ if [ $num -gt 200 ];________________________________________ then________________________________________________________ echo "Eligible for 20% discount"____________________________ ____________________________________________________________ elif [[ $num == 200 || $num == 100 ]];______________________ then________________________________________________________ echo "Lucky Draw Winner"____________________________________ echo "Eligible to get the item for free"____________________ ____________________________________________________________ elif [[ $num -gt 100 && $num -lt 200 ]];____________________ then________________________________________________________ echo "Eligible for 10% discount"____________________________ ____________________________________________________________ elif [ $num -lt 100 ];______________________________________ then________________________________________________________ echo "No discount"__________________________________________ fi__________________________________________________________ Bash Case ==================================================================================================== In this topic, we will discuss the basics of case statements and how to use them in Bash scripts. The Bash case statement is the simplest form of IF-THEN-ELSE with many ELIF elements. Using the case statement makes our bash script more readable and easier to maintain. These are generally applied to simplify the complex conditions having multiple different choices. The Bash case statement follows a similar logic as the Javascript or C switch statement. There is a slight difference, as follows: * The Bash case statement takes a value once and tests that value multiple times. It stops searching for a pattern once it has found it and executed the statement linked with it, which is almost opposite in case of the C switch statement. Case Statement Syntax Syntax of the bash case statement is given below: case expression in_____________________________________ pattern_1)____________________________________________ statements___________________________________________ ;;___________________________________________________ pattern_2)_________________________________________________ statements________________________________________________ ;;________________________________________________________ pattern_3|pattern_4|pattern_5)_____________________________ statements________________________________________________ ;;________________________________________________________ pattern-n)_________________________________________________ statements________________________________________________ ;;________________________________________________________ *)_________________________________________________________ statements________________________________________________ ;;________________________________________________________ esac________________________________________________________ There are some key points of bash case statements: * Each case statement in bash starts with the 'case' keyword, followed by the case expression and 'in' keyword. The case statement is closed by 'esac' keyword. * We can apply multiple patterns separated by | operator. The ) operator indicates the termination of a pattern list. * A pattern containing the statements is referred to as a clause, and it must be terminated by double semicolon (;;). * An asterisk symbol (*) is used as a final pattern to define the default case. It is used as a default case when used as the last case. How it works First of all, the case statement expands the expression and tries to match with each of the included patterns. When it finds a match, all the linked statements are executed till the double semicolon (;;). After the first match, case terminates with the exit status of the last executed statement. If there is no matched pattern, the exit status of the case is zero. Otherwise, the return status is the exit status of the executed statements. If the default asterisk pattern is used, it will be executed in case of no matched pattern. Let's try to understand this mechanism with the help of a few examples: Example 1 In this example, we have defined a simple scenario to demonstrate the use of the case statement. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ echo "Do you know Java Programming?"___________________ read -p "Yes/No? :" Answer_____________________________ case $Answer in_____________________________________________ Yes|yes|y|Y)_______________________________________________ echo "That's amazing."____________________________________ echo______________________________________________________ ;;________________________________________________________ No|no|N|n)_________________________________________________ echo "It's easy. Let's start learning from javatpoint_____ ;;________________________________________________________ esac________________________________________________________ Example 2 In this example, we have defined a combined scenario where there is also a default case when no previous matched case is found. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ echo "Which Operating System are you using?"___________ echo "Windows, Android, Chrome, Linux, Others?"________ read -p "Type your OS Name:" OS_____________________________ ____________________________________________________________ case $OS in_________________________________________________ Windows|windows)___________________________________________ echo "That's common. You should try something new."_______ echo______________________________________________________ ;;________________________________________________________ Android|android)___________________________________________ echo "This is my favorite. It has lots of application_____ echo______________________________________________________ ;;________________________________________________________ Chrome|chrome)_____________________________________________ echo "Cool!!! It's for pro users. Amazing Choice."________ echo______________________________________________________ ;;________________________________________________________ Linux|linux)_______________________________________________ echo "You might be serious about security!!"______________ echo______________________________________________________ ;;________________________________________________________ *)_________________________________________________________ echo "Sounds interesting. I will try that."_______________ echo______________________________________________________ ;;________________________________________________________ esac________________________________________________________ Bash For Loop ==================================================================================================== In this topic, we will understand the usage of for loop in Bash scripts. Like any other programming language, bash shell scripting also supports 'for loops' to perform repetitive tasks. It helps us to iterate a particular set of statements over a series of words in a string, or elements in an array. For example, you can either run UNIX command (or task) many times or just read and process the list of commands using a 'for loop'. Syntax of For Loop We can apply 'for loop' on bash script in two ways. One way is 'for-in' and another way is the c-style syntax. Following is the syntax of 'for loop' in bash shell scripting: for variable in list___________________________________ do_____________________________________________________ commands_______________________________________________ done___________________________________________________ Or for (( expression1; expression2; expression3 ))________ do_____________________________________________________ commands_______________________________________________ done___________________________________________________ There are some key points of 'for loop' statement: * Each block of 'for loop' in bash starts with 'do' keyword followed by the commands inside the block. The 'for loop' statement is closed by 'done' keyword. * The number of time for which a 'for loop' will iterate depends on the declared list variables. * The loop will select one item from the list and assign the value on a variable which will be used within the loop. * After the execution of commands between 'do' and 'done', the loop goes back to the top and select the next item from the list and repeat the whole process. * The list can contain numbers or string etc. separated by spaces. Some of the 'for loop' examples are given below to illustrate how do they work: Basic 'For Loop' Example Bash Script #!/bin/bash____________________________________________ #This is the basic example of 'for loop'.______________ _______________________________________________________ learn="Start learning from Javatpoint."________________ ____________________________________________________________ for learn in $learn_________________________________________ do__________________________________________________________ echo $learn_________________________________________________ done________________________________________________________ ____________________________________________________________ echo "Thank You."___________________________________________ For Loop to Read a Range Bash Script #!/bin/bash____________________________________________ #This is the basic example to print a series of numbers _______________________________________________________ for num in {1..10}_____________________________________ do__________________________________________________________ echo $num___________________________________________________ done________________________________________________________ ____________________________________________________________ echo "Series of numbers from 1 to 10."______________________ For Loop to Read a Range with Increment/Decrement We can increase or decrease a specified value by adding two another dots (..) and the value to step by, e.g., {START..END..INCREMENT}. Check out the example below: For Increment #!/bin/bash____________________________________________ _______________________________________________________ #For Loop to Read a Range with Increment_______________ _______________________________________________________ for num in {1..10..1}_______________________________________ do__________________________________________________________ echo $num___________________________________________________ done________________________________________________________ For Decreament #!/bin/bash____________________________________________ _______________________________________________________ #For Loop to Read a Range with Decrement_______________ _______________________________________________________ for num in {10..0..1}_______________________________________ do__________________________________________________________ echo $num___________________________________________________ done________________________________________________________ For Loop to Read Array Variables We can use 'for loop' to iterate the values of an array. The syntax can be defined as: array=( "element1" "element 2" . . "elementN" )_____ _______________________________________________________ for i in "${arr[@]}"___________________________________ do_____________________________________________________ echo $i_____________________________________________________ done________________________________________________________ For each element in 'array', the statements or set of commands from 'do' till 'done' are executed. Each element could be accessed as 'i' within the loop for the respective iteration. Check out the example below explaining the use of 'for loop' to iterate over elements of an array: Bash Script #!/bin/bash____________________________________________ _______________________________________________________ #Array Declaration_____________________________________ arr=( "Welcome""to""Javatpoint" )______________________ ____________________________________________________________ for i in "${arr[@]}"________________________________________ do__________________________________________________________ echo $i_____________________________________________________ done________________________________________________________ For Loop to Read white spaces in String as word separators The syntax can be defined as below: #!/bin/bash____________________________________________ _______________________________________________________ for word in $str;______________________________________ do_____________________________________________________ ________________________________________________ done________________________________________________________ Here, str refers to a string. The statements from 'do' till 'done' are executed for each 'word' of a string. Check out the example below: Bash Script #!/bin/bash____________________________________________ #For Loop to Read white spaces in String as word separa _______________________________________________________ str="Let's start_______________________________________ learning from Javatpoint."__________________________________ ____________________________________________________________ for i in $str;______________________________________________ do__________________________________________________________ echo "$i"___________________________________________________ done________________________________________________________ For Loop to Read each line in String as a word The syntax can be defined as below: #!/bin/bash____________________________________________ _______________________________________________________ for word in "$str";____________________________________ do_____________________________________________________ ________________________________________________ done________________________________________________________ Here, the statements from 'do' till 'done' are executed for each 'line' of a string. Check out the example below: Bash Script #!/bin/bash____________________________________________ #For Loop to Read each line in String as a word________ _______________________________________________________ str="Let's start_______________________________________ learning from ______________________________________________ Javatpoint."________________________________________________ ____________________________________________________________ for i in "$str";____________________________________________ do__________________________________________________________ echo "$i"___________________________________________________ done________________________________________________________ Note: The only difference between 'For Loop to Read white spaces in String as word separators' and 'For Loop to Read each line in String as a word' is the double quotes around string variable. For Loop to Read Three-expression Three expression syntax is the most common syntax of 'for loop'. The first expression refers to the process of initialization, the second expression refers to the termination, and the third expression refers to the increment or decrement. Check out the example below to print 1 to 10 numbers using three expressions with for loop: Bash Script #!/bin/bash____________________________________________ #For Loop to Read Three-expression_____________________ _______________________________________________________ for ((i=1; i<=10; i++))________________________________ do__________________________________________________________ echo "$i"___________________________________________________ done________________________________________________________ For Loop with a Break Statement A 'break' statement can be used inside 'for' loop to terminate from the loop. Bash Script #!/bin/bash____________________________________________ #Table of 2____________________________________________ _______________________________________________________ for table in {2..100..2}_______________________________ do__________________________________________________________ echo $table_________________________________________________ if [ $table == 20 ]; then___________________________________ break_______________________________________________________ fi__________________________________________________________ done________________________________________________________ For Loop with a Continue Statement We can use the 'continue' statement inside the 'for' loop to skip any specific statement on a particular condition. It tells Bash to stop executing that particular iteration of the loop and process the next iteration. Bash Script #!/bin/bash____________________________________________ #Numbers from 1 to 20, ignoring from 6 to 15 using cont _______________________________________________________ for ((i=1; i<=20; i++));_______________________________ do__________________________________________________________ if [[ $i -gt 5 && $i -lt 16 ]];_____________________________ then________________________________________________________ continue____________________________________________________ fi__________________________________________________________ echo $i_____________________________________________________ done________________________________________________________ Infinite Bash For Loop When there is no 'start, condition, and increment' in the bash three expressions for loop, it becomes an infinite loop. To terminate the infinite loop in Bash, we can press Ctrl+C. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ i=1;___________________________________________________ for (( ; ; ))__________________________________________ do__________________________________________________________ sleep 1s____________________________________________________ echo "Current Number: $((i++))"_____________________________ done________________________________________________________ Bash While Loop ==================================================================================================== In this topic, we have demonstrated how to use while loop statement in Bash Script. The bash while loop can be defined as a control flow statement which allows executing the given set of commands repeatedly as long as the applied condition evaluates to true. For example, we can either run echo command many times or just read a text file line by line and process the result by using while loop in Bash. Syntax of Bash While Loop Bash while loop has the following format: while [ expression ];__________________________________ do_____________________________________________________ commands;______________________________________________ multiple commands;_____________________________________ done________________________________________________________ The above syntax is applicable only if the expression contains a single condition. If there are multiple conditions to include in the expression, then the syntax of the while loop will be as follows: while [ expressions ];_________________________________ do_____________________________________________________ commands;______________________________________________ multiple commands;_____________________________________ done________________________________________________________ The while loop one-liner syntax can be defined as: while [ condition ]; do commands; done_________________ while control-command; do Commands; done_______________ There are some key points of 'while loop' statement: * The condition is checked before executing the commands. * The 'while' loop is also capable of performing all the work as for 'loop' can do. * The commands between 'do' and 'done' are repeatedly executed as long as the condition evaluates to true. * The arguments for a 'while' loop can be a boolean expression. How it works The while loop is a restricted entry loop. It means that the condition is checked before executing the commands of the while loop. If the condition evaluates to true, the set of commands following that condition are executed. Otherwise, the loop is terminated, and the program control is given to the other command following the 'done' statement. Bash While Loop Examples Following are some examples of bash while loop: While Loop with Single Condition In this example, the while loop is used with a single condition in expression. It is the basic example of while loop which will print series of numbers as per user input: Example #!/bin/bash____________________________________________ #Script to get specified numbers_______________________ _______________________________________________________ read -p "Enter starting number: " snum_________________ read -p "Enter ending number: " enum________________________ ____________________________________________________________ while [[ $snum -le $enum ]];________________________________ do__________________________________________________________ echo $snum__________________________________________________ ((snum++))__________________________________________________ done________________________________________________________ ____________________________________________________________ echo "This is the sequence that you wanted."________________ Output Bash While Loop While Loop with Multiple Conditions Following is an example of while loop with multiple conditions in the expression: Example #!/bin/bash____________________________________________ #Script to get specified numbers_______________________ _______________________________________________________ read -p "Enter starting number: " snum_________________ read -p "Enter ending number: " enum________________________ ____________________________________________________________ while [[ $snum -lt $enum || $snum == $enum ]];______________ do__________________________________________________________ echo $snum__________________________________________________ ((snum++))__________________________________________________ done________________________________________________________ ____________________________________________________________ echo "This is the sequence that you wanted."________________ Infinite While Loop An infinite loop is a loop that has no ending or termination. If the condition always evaluates to true, it creates an infinite loop. The loop will execute continuously until it is forcefully stopped using CTRL+C : Example #!/bin/bash____________________________________________ #An infinite while loop________________________________ _______________________________________________________ while :________________________________________________ do__________________________________________________________ echo "Welcome to Javatpoint."_______________________________ done________________________________________________________ We can also write the above script in a single line as: #!/bin/bash____________________________________________ #An infinite while loop________________________________ _______________________________________________________ while :; do echo "Welcome to Javatpoint."; done________ Here, we have used the built-in command (:) which always return true. We can also use the built-in command true to create an infinite loop just as below: Example #!/bin/bash____________________________________________ #An infinite while loop________________________________ _______________________________________________________ while true_____________________________________________ do__________________________________________________________ echo "Welcome to Javatpoint"________________________________ done________________________________________________________ This bash script will also provide the same output as an above infinite script. Note: Infinite loops can be terminated by using CTRL+C or by adding some conditional exit within the script. While Loop with a Break Statement A break statement can be used to stop the loop as per the applied condition. For example: Example #!/bin/bash____________________________________________ #While Loop Example with a Break Statement_____________ _______________________________________________________ echo "Countdown for Website Launching..."______________ i=10________________________________________________________ while [ $i -ge 1 ]__________________________________________ do__________________________________________________________ if [ $i == 2 ]______________________________________________ then________________________________________________________ echo "Mission Aborted, Some Technical Error Found."________ break______________________________________________________ fi__________________________________________________________ echo "$i"___________________________________________________ (( i-- ))___________________________________________________ done________________________________________________________ According to the script, the loop is assigned to iterate for ten times. But there is a condition after eight times of iteration which will break the iteration and terminate the loop. The following output will be shown after executing the script. Bash While Loop While Loop with a Continue Statement A continue statement can be used to skip the iteration for a specific condition inside the while loop. Example #!/bin/bash____________________________________________ #While Loop Example with a Continue Statement__________ _______________________________________________________ i=0____________________________________________________ while [ $i -le 10 ]_________________________________________ do__________________________________________________________ ((i++))_____________________________________________________ if [[ "$i" == 5 ]];_________________________________________ then________________________________________________________ continue___________________________________________________ fi__________________________________________________________ echo "Current Number : $i"__________________________________ done________________________________________________________ ____________________________________________________________ echo "Skipped number 5 using Continue Statement."___________ Output Bash While Loop While Loop with C-Style We can also write while loop in bash script as similar as a while loop in C programming language. Example #!/bin/bash____________________________________________ #While loop example in C style_________________________ _______________________________________________________ i=1____________________________________________________ while((i <= 10))____________________________________________ do__________________________________________________________ echo $i_____________________________________________________ let i++_____________________________________________________ done________________________________________________________ Bash Until Loop ==================================================================================================== In this topic, we have defined how to use until loop statement in Bash Script. The while loop is a great option to execute a set of commands when some condition evaluates to true. Sometimes, we need to execute a set of commands until a condition evaluates to true. In such cases, Bash until loop is useful. Bash Until Loop in a bash scripting is used to execute a set of commands repeatedly based on the boolean result of an expression. The set of commands are executed only until the expression evaluates to true. It means that when the expression evaluates to false, a set of commands are executed iteratively. The loop is terminated as soon as the expression evaluates to true for the first time. In short, the until loop is similar to the while loop but with a reverse concept. Syntax The syntax of until loop looks almost similar to the syntax of bash while loop. But there is a big difference in the functionalities of both. The syntax of bash until loop can be defined as: until [ expression ];__________________________________ do_____________________________________________________ command1_______________________________________________ command2_______________________________________________ . . ._______________________________________________________ . . . . ____________________________________________________ commandN____________________________________________________ done________________________________________________________ If there are multiple conditions in the expression, then the syntax will be as follows: until [[ expression ]];________________________________ do_____________________________________________________ command1_______________________________________________ command2_______________________________________________ . . ._______________________________________________________ . . . . ____________________________________________________ commandN____________________________________________________ done________________________________________________________ Some of the key points of until loop are given below: * The condition is checked before executing the commands. * The commands are only executed if the condition evaluates to false. * The loop is terminated as soon as the condition evaluates to true. * The program control is transferred to the command that follows the 'done' keyword after the termination. The while loop vs. the until loop * The 'until loop' commands execute until a non-zero status is returned. * The 'while loop' commands execute until a zero status is returned. * The until loop contains property to be executed at least once. Examples of Bash Until Loop Following are some examples of bash until loop illustrating different scenarios to help you understand the usage and working of it: Until Loop with Single Condition In this example, the until loop contains a single condition in expression. It is the basic example of until loop which will print series of numbers from 1 to 10: Example #!/bin/bash____________________________________________ #Bash Until Loop example with a single condition_______ _______________________________________________________ i=1____________________________________________________ until [ $i -gt 10 ]_________________________________________ do__________________________________________________________ echo $i_____________________________________________________ ((i++))_____________________________________________________ done________________________________________________________ Until Loop with Multiple Conditions Following is an example with multiple conditions in an expression: Example #!/bin/bash____________________________________________ #Bash Until Loop example with multiple conditions______ _______________________________________________________ max=5__________________________________________________ a=1_________________________________________________________ b=0_________________________________________________________ ____________________________________________________________ until [[ $a -gt $max || $b -gt $max ]];_____________________ do__________________________________________________________ echo "a = $a & b = $b."_____________________________________ ((a++))_____________________________________________________ ((b++))_____________________________________________________ done________________________________________________________ Bash String ==================================================================================================== In this topic, we have demonstrated about bash string and its operators. Like other programming languages, Bash String is a data type such as as an integer or floating-point unit. It is used to represent text rather than numbers. It is a combination of a set of characters that may also contain numbers. For example, the word "javatpoint" and the phrase "Welcome to javatpoint" are the strings. Even "01234" could be considered as a string, if specified correctly. Programmers are required to enclose strings in quotation marks for the data to be considered as a string and not a number, variable name or array, etc. Bash consists of multiple ways to perform string operations and manipulate them. Following are some operators in Shell Script used to perform string operations: Equal Operator An equal operator (=) is used to check whether two strings are equal. Syntax Operand1 = Operand2____________________________________ Example #!/bin/bash____________________________________________ #Script to check whether two strings are equal.________ _______________________________________________________ str1="WelcometoJavatpoint."____________________________ str2="javatpoint"___________________________________________ ____________________________________________________________ if [ $str1 = $str2 ];_______________________________________ then________________________________________________________ echo "Both the strings are equal."__________________________ else________________________________________________________ echo "Strings are not equal."_______________________________ fi__________________________________________________________ Not Equal Operator Not equal operator (!=) is used to define that strings are not equal. Syntax Operand1 != Operand2___________________________________ Example #!/bin/bash____________________________________________ #Script to check whether two strings are equal.________ _______________________________________________________ str1="WelcometoJavatpoint."____________________________ str2="javatpoint"___________________________________________ ____________________________________________________________ if [[ $str1 != $str2 ]];____________________________________ then________________________________________________________ echo "Strings are not equal."_______________________________ else________________________________________________________ echo "Strings are equal."___________________________________ fi__________________________________________________________ Less than Operator The 'less than operator (\<)' is a conditional operator which is used to check if string1 is less than string2. Syntax Operand1 \< Operand2___________________________________ Example #!/bin/sh _____________________________________________ _______________________________________________________ str1="WelcometoJavatpoint"_____________________________ str2="Javatpoint"______________________________________ if [ $str1 \< $str2 ];______________________________________ then _______________________________________________________ echo "$str1 is less then $str2"____________________________ else________________________________________________________ echo "$str1 is not less then $str2"________________________ fi__________________________________________________________ Greater than Operator The 'greater than operator (\>)` is used to check if string1 is greater than string2. Syntax Operand1 \> Operand2___________________________________ Example #!/bin/sh _____________________________________________ _______________________________________________________ str1="WelcometoJavatpoint"_____________________________ str2="Javatpoint"______________________________________ if [ $str1 \> $str2 ];______________________________________ then _______________________________________________________ echo "$str1 is greater then $str2"_________________________ else________________________________________________________ echo "$str1 is less then $str2"____________________________ fi__________________________________________________________ To check if the string length is greater than Zero: This operator is used to check if the string is zero or greater than zero. Syntax [ -n Operand ]_________________________________________ Example #!/bin/sh _____________________________________________ _______________________________________________________ str="WelcometoJavatpoint"______________________________ _______________________________________________________ if [ -n $str ];_____________________________________________ then _______________________________________________________ echo "String is not empty"_________________________________ else________________________________________________________ echo "String is empty"_____________________________________ fi _________________________________________________________ To check if the string length is equal to Zero This operator is used to check if the string is empty or equal to zero. Syntax [ -z Operand ]_________________________________________ Example #!/bin/sh _____________________________________________ _______________________________________________________ str=""_________________________________________________ _______________________________________________________ if [ -z $str ];_____________________________________________ then _______________________________________________________ echo "String is empty."____________________________________ else________________________________________________________ echo "String is non-empty."________________________________ fi _________________________________________________________ Bash Find ==================================================================================================== In this topic, we have demonstrated about finding the length of a string in Bash Scripting. The total number of characters in any string indicates the length of a string. In some cases, we might need to know about the length of a string to perform some specific tasks. Most of the programming languages have their own built-in functions to calculate the number of characters. However, Bash does not contain such type of built-in functions. But there are several ways that we can use to find the length of a string in Bash Scripting. Bash StringLength To calculate the length of a string, we can use any of the following syntax: 1. ${#string}__________________________________________ 2. expr length "$string"_______________________________ 3. expr "$string" :'.*'________________________________ 4. $str | wc -c________________________________________ 5. $str |awk '{print length}'_______________________________ Note: Observe the double quotes used around $string. If a string has spaces in it, then double quotes are very important. Otherwise, it can be ignored. We recommend to always use double quotes around $string to be on the safe side. The above syntax defines that we can find the length of a string with or without bash command. Using '#' sign, we can calculate the length of a string without applying any bash command. Let's understand it more clearly with the help of some examples: Examples to find String Length in Bash There are some examples given below illustrating the different ways to find a string length in bash shell scripting: Example 1 The simplest way to calculate the length of a string is to use '#' symbol. In this example, we have used $[#string_variable_name} to find the length of a string. Bash Script #!/bin/bash____________________________________________ #Bash program to find the length of a string___________ _______________________________________________________ str="Welcome to Javatpoint"____________________________ length=${#str}______________________________________________ ____________________________________________________________ echo "Length of '$str' is $length"__________________________ Example 2 Another way to calculate the length of a string is to use `expr` command with the 'length' keyword. In this example, we have used `expr length "$str"` to find the length of a string. Bash Script #!/bin/bash____________________________________________ #Bash script to find the length of a string____________ _______________________________________________________ str="Welcome to Javatpoint"____________________________ length=`expr length "$str"`_________________________________ ____________________________________________________________ echo "Length of '$str' is $length"__________________________ Example 3 In this example, we have used `expr "$str": ' .*'`to find the length of a string. Here, str is a string variable. Bash Script #!/bin/bash____________________________________________ #Bash script to find the length of a string____________ _______________________________________________________ str="Welcome to Javatpoint"____________________________ length=`expr "$str" : '.*'`_________________________________ ____________________________________________________________ echo "Length of '$str' is $length"__________________________ Example 4 In this example, we have used `wc` command to find the length of a string. Bash Script #!/bin/bash____________________________________________ #Bash script to find the length of a string____________ _______________________________________________________ str="Welcome to Javatpoint"____________________________ length=`echo $str | wc -c`__________________________________ ____________________________________________________________ echo "Length of '$str' is $length"__________________________ Example 5 In this example, we have used `awk` command to find the length of a string. Bash Script #!/bin/bash____________________________________________ #Bash script to find the length of a string____________ _______________________________________________________ str="Welcome to Javatpoint"____________________________ length=`echo $str |awk '{print length}'`____________________ ____________________________________________________________ echo "Length of '$str' is $length"__________________________ Bash Split String ==================================================================================================== In this topic, we have defined how to split a string in bash shell scripting. In some cases, we might need to split the string data to perform some specific tasks. Most of the programming languages contain built-in function 'split' to divide any string data into multiple parts. However, bash does not contain such type of built-in function. But we can use delimiters to split any string data in bash scripting. The delimiter can be either a single character or a string with multiple characters. Check out the methods below to understand how to split string in a bash shell: Split using $IFS variable Following are the steps to split a string in bash using $IFS: * $IFS is a special internal variable which is used to split a string into words. $IFS variable is called 'Internal Field Separator' which determines how Bash recognizes boundaries. $IFS is used to assign the specific delimiter [ IFS=''] for dividing the string. The white space is a default value of $IFS. However, we can also use values such as '\t', '\n', '-' etc. as the delimiter. * After assigning the delimiter, a string can be read by two options: '-r' and '-a'. i.e., read -ra ARR <<< "$str". Here, the option '-r' is used to define that backslash (\) is a character rather than escape character. The '-a' option is used to define that the words (separated by $IFS) are assigned to the sequential index of array beginning at zero. * Then we apply bash 'for' loop to access the tokens which are split into an array. Let's understand this mechanism with the help of some examples: Example 1: Bash Split String by Space In this example, a string is split using a space character delimiter. Bash Script #!/bin/bash____________________________________________ #Example for bash split string by space________________ _______________________________________________________ read -p "Enter any string separated by space: " str #r ____________________________________________________________ IFS='' #setting space as delimiter__________________________ read -ra ADDR <<<"$str" #reading str as an array as tok_____ ____________________________________________________________ for i in "${ADDR[@]}"; #accessing each element of array_____ do__________________________________________________________ echo "$i"___________________________________________________ done________________________________________________________ Example 2: Bash Split String by Symbol In some cases, we may have a requirement to split a string by other delimiters such as a symbol or specific character. In this example, a string is split using a comma (,) symbol character as a delimiter. Bash Script #!/bin/bash____________________________________________ #Example for bash split string by Symbol (comma)_______ _______________________________________________________ read -p "Enter Name, State and Age separated by a comma ____________________________________________________________ IFS=',' #setting comma as delimiter_________________________ read -a strarr <<<"$entry" #reading str as an array as _____ ____________________________________________________________ echo "Name : ${strarr[0]} "_________________________________ echo "State : ${strarr[1]} "________________________________ echo "Age : ${strarr[2]}"___________________________________ Split without $IFS variable In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form. Let's understand this logic with the help of some example: Example 1: Bash Split String by Symbol This example defines how a string value can be split without using $IFS. As per the script, a text value should be entered with the colon (:) sign so that it can be split. Check out the bash script below: Bash Script #!/bin/bash____________________________________________ #Example for bash split string without $IFS____________ _______________________________________________________ read -p "Enter any string separated by colon(:) " str # ____________________________________________________________ readarray -d : -t strarr <<<"$str" #split a string base_____ ____________________________________________________________ printf "\n"_________________________________________________ ____________________________________________________________ #Print each value of Array with the help of loop____________ for (( n=0; n < ${#strarr[*]}; n++ ))_______________________ do__________________________________________________________ echo "${strarr[n]}"_________________________________________ done________________________________________________________ Example 2: Bash Split String by another string In this example, we have used idiomatic expressions where parameter expansion has completed. Bash Script #!/bin/bash____________________________________________ #Example for bash split string by another string_______ _______________________________________________________ str="WeLearnWelcomeLearnYouLearnOnLearnJavatpoint"_____ delimiter=Learn_____________________________________________ s=$str$delimiter____________________________________________ array=();___________________________________________________ while [[ $s ]];_____________________________________________ do__________________________________________________________ array+=( "${s%%"$delimiter"*}" );___________________________ s=${s#*"$delimiter"};_______________________________________ done;_______________________________________________________ declare -p array____________________________________________ In this bash script, we have used the following Parameter- Expansions: * ${parameter%%word} It removes the longest matching suffix pattern. * ${parameter#word} It removes the shortest matching prefix pattern. Example 3: Bash Split String using Trim Command In this example, we have used trim (tr) command to split a string. Instead of using the read command, the trim command is used to split a string on the delimiter. Bash Script #!/bin/bash____________________________________________ #Example to split a string using trim (tr) command_____ _______________________________________________________ my_str="We;welcome;you;on;javatpoint."_________________ my_arr=($(echo $my_str | tr ";""\n"))_______________________ ____________________________________________________________ for i in "${my_arr[@]}"_____________________________________ do__________________________________________________________ echo $i_____________________________________________________ done________________________________________________________ Note: It should be noted that array elements are divided on 'space delimiter' if we apply a trim command to split a string. For example, elements like 'Windows OS' will be treated as two different words. Bash Substring ==================================================================================================== In this topic, we have explained how to compute substring of a given string. A substring is a sequence of characters within a string. Bash provides an option to extract the information from a string itself. You can extract the digits or a given string using several methods. For example, "welcome you on Javatpoint." is a substring of "We welcome you on Javatpoint." Syntax The command for the extraction of substring is a build-in bash command, and so it is very good to use for performance perspective. The syntax of the substring extraction can be defined as: ${variable:offset:length}______________________________ where, Variable is the variable name that contains a string. Offset is used to specify the position from where to start the extraction of a string. Length is used to specify the range of the characters to be executed from the offset. Note: Assigning length is optional. If length is not provided, then end of the string will be considered as the end of the substring. Let's understand the concept of extracting a substring from the string with the help of some examples: Example 1: To Extract till Specific Characters from Starting #!/bin/bash____________________________________________ #Script to extract first 10 characters of a string_____ _______________________________________________________ echo "String: We welcome you on Javatpoint."___________ str="We welcome you on Javatpoint."_________________________ ____________________________________________________________ echo "Total characters in a String: ${#str} "_______________ ____________________________________________________________ substr="${str:0:10}"________________________________________ ____________________________________________________________ echo "Substring: $substr"___________________________________ echo "Total characters in Substring: ${#substr} "___________ Example 2: To Extract from Specific Character onwards #!/bin/bash____________________________________________ #Script to print from 11th character onwards___________ _______________________________________________________ str="We welcome you on Javatpoint."____________________ substr="${str:11}"__________________________________________ echo "$substr"______________________________________________ Here, end of the string is considered as the end of the substring. Example 3: To Extract a Single Character #!/bin/bash____________________________________________ #Script to print 11th character of a String____________ _______________________________________________________ str="We welcome you on Javatpoint."____________________ substr="${str:11:1}"________________________________________ echo "$substr"______________________________________________ Example 4: To Extract the specific characters from last #!/bin/bash____________________________________________ #Script to extract 11 characters from last_____________ _______________________________________________________ str="We welcome you on Javatpoint."____________________ substr="${str:(-11)}"_______________________________________ echo "$substr"______________________________________________ Bash Concatenate String ==================================================================================================== In this topic, we have explained how to add or concatenate strings in Bash Shell Scripting. In bash scripting, we can add or join two or more strings together, which is known as string concatenation. It is one of the common requirement for any programming language. A special character or built-in function is applied to perform string concatenation. However, Bash does not contain any built-in function to combine string data or variables. The easiest method to perform string concatenation in bash is to write variables side by side. For example, assume that we have two strings (i.e., "welcome" & "to javatpoint"), and we join both the strings together and a new string ("welcome to javatpoint") is created. This concept is referred to as String Concatenation. Command The example command for concatenating the strings can be defined as: str3="$str1$str2"______________________________________ Note: Observe the above command; there should not be any space before or after the assignment (=) operator. 'str' is used to indicate strings. This command will concatenate the values of str1 and str2 and store it in a third variable str3. Following are some examples demonstrating the different ways of string concatenation: Example 1: Write Variables Side by Side This is the basic example of String Concatenation, and we do not need any extra operator or function in this method. Bash Script #!/bin/bash____________________________________________ #Script to Concatenate Strings_________________________ _______________________________________________________ #Declaring the first String ___________________________ str1="We welcome you"_______________________________________ ____________________________________________________________ #Declaring the Second String________________________________ str2=" on Javatpoint."______________________________________ ____________________________________________________________ #Combining first and second string__________________________ str3="$str1$str2"___________________________________________ ____________________________________________________________ #Printing a new string by combining both ___________________ echo $str3__________________________________________________ Example 2: Using Double Quotes Another easy method is to use variables inside the string, which is defined with double-quotes. The string variable can be applied in any position of the string data. Bash Script #!/bin/bash____________________________________________ #Script to Concatenate Strings_________________________ _______________________________________________________ #Declaring String Variable_____________________________ str="We welcome you"________________________________________ ____________________________________________________________ #Add the variable within the string_________________________ echo "$str on Javatpoint."__________________________________ Example 3: Using Append Operator with Loop Most of the popular programming languages provide support for append operator (+=) which is the combination of the plus and equal sign. It will add new strings to the end of the string variable. Bash Script #!/bin/bash____________________________________________ echo "Printing the name of the programming languages"__ #Initializing the variable before combining____________ lang=""________________________________________________ #for loop for reading the list______________________________ for value in 'java''python''C''C++';________________________ do__________________________________________________________ lang+="$value " #Combining the list values using appen_____ done________________________________________________________ #Printing the combined values_______________________________ echo "$lang"________________________________________________ Example 4: Using the Printf Function In bash, printf is a function which is used to print and concatenate the strings. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ str="Welcome"__________________________________________ printf -v new_str "$str to Javatpoint."________________ echo $new_str_______________________________________________ Example 5: Using Literal Strings String concatenation can also be performed with a literal string by using curly braces{}. They should be used in such a way that the variable does not mix up with the literal string. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ str="Welcome to"_______________________________________ _______________________________________________________ newstr="${str} Javatpoint."_________________________________ echo "$newstr"______________________________________________ Example 6: Using Underscore Using underscore for concatenating the string in bash shell is one of the common tasks. It is mostly used for assigning a name to the files. Bash Script #!/bin/bash____________________________________________ _______________________________________________________ str1="Hello"___________________________________________ str2="World!"__________________________________________ ____________________________________________________________ echo "${str1}_${str2}"______________________________________ Example 7: Using any Character Bash Script #!/bin/bash____________________________________________ #String Concatenation by Character (,) with User Input_ _______________________________________________________ read -p "Enter First Name: " name______________________ read -p "Enter State: " state_______________________________ read -p "Enter Age: " age___________________________________ ____________________________________________________________ combine="$name,$state,$age"_________________________________ ____________________________________________________________ echo "Name, State, Age: $combine"___________________________ Bash Functions ==================================================================================================== In this topic, we have demonstrated the basics of bash functions and how they work in bash shell scripting. Functions in bash scripting are a great option to reuse code. A Bash function can be defined as a set of commands which can be called several times within bash script. The purpose of function in bash is to help you make your scripts more readable and avoid writing the same code again and again. It also allows the developers to break a complicated and lengthy code to small parts which can be called whenever required. Functions can be called anytime and repeatedly, which will enable us to reuse, optimize, and minimize the code. Following are some key points about bash functions: * A function has to be declared in the shell script before we can use it. * Arguments can be passed to the functions and accessed inside the function as $1, $2, etc. * Local variables can be assigned within the function, and the scope of such variables will only be that particular function. * Built-in commands of Bash shell can be overridden using functions. Syntax The syntax for declaring a bash function can be defined in two formats: 1. The first method starts with the function name, followed by parentheses. It is the most preferred and commonly used method: function_name () {_____________________________________ commands_______________________________________________ }______________________________________________________ Single line version can be mentioned as below: function_name () { commands; }_________________________ 2. The second method starts with the function reserved word, followed by the function name: function function_name {_______________________________ commands_______________________________________________ }______________________________________________________ Single line version can be mentioned as below: function function_name { commands; }___________________ Compared to most of the programming languages, Bash functions are somewhat limited. Let?s understand the concept with the help of some examples: Example: Method 1 #!/bin/bash____________________________________________ _______________________________________________________ JTP () {_______________________________________________ echo 'Welcome to Javatpoint.'_________________________ }___________________________________________________________ ____________________________________________________________ JTP_________________________________________________________ Example: Method 2 #!/bin/bash____________________________________________ _______________________________________________________ function JTP {_________________________________________ echo 'Welcome to Javatpoint.'_________________________ }___________________________________________________________ ____________________________________________________________ JTP_________________________________________________________ Passing Arguments Like most of the programming languages, we can also pass the arguments and process the data in bash functions. We can insert the data to the function in a similar way as passing-command line arguments to a bash script. To pass any number of arguments to the bash function, we are required to insert them just after the function's name. We must apply spaces between function name and arguments. It will also be a great choice to use double quotes around the arguments to prevent misparsing of the arguments with spaces in it. Following are some key points about passing arguments to the bash functions: * The given arguments are accessed as $1, $2, $3 ... $n, corresponding to the position of the arguments after the function's name. * The $0 variable is kept reserved for the function's name. * The $# variable is used to hold the number of positional argument/ parameter given to the function. * The $* and $@ variables are used to hold all the arguments/ parameters given to the function. + When $* is used with double quotes (i.e., "$*" ), it expands to a single string separated by the space. For example, "$1 $2 $n etc". + When $@ is used with double quotes (i.e., "$@" ), it expands to the separate string. For example, "$1" "$2" "$n" etc. + When $* and $# are not used with the double quotes, they both are the same. Following isthe code that illustrates the procedure on how to pass arguments to functions, and access the arguments inside the function. Bash Script #!/bin/bash____________________________________________ #Script to pass and access arguments___________________ _______________________________________________________ function_arguments()___________________________________ {__________________________________________________________ echo $1____________________________________________________ echo $2____________________________________________________ echo $3____________________________________________________ echo $4____________________________________________________ echo $5____________________________________________________ }__________________________________________________________ ____________________________________________________________ #Calling function_arguments_________________________________ function_arguments "We""welcome""you""on""Javatpoint."______ In this script, we have added the values "We", "welcome", "you", "on" and "Javatpoint" after we have called the function_arguments. Those values are passed to the function_arguments as parameters and stored in a local variable. However, unlike other languages, the interpreter stores the passed values into predefined variables, which are then named according to the sequence of passing parameters. For example, "We" word is stored to the variable 1. "welcome" word is stored to the variable 2. "you" word is stored to the variable 3. "on" word is stored to the variable 4. "Javatpoint" word is stored to the variable 5. Variable Scope Global variables are defined as the variables which can be accessed anywhere within the script regardless of the scope. By default, all the variables are defined as global variables, even if they are declared inside the function. We can also create variables as a local variable. Local variables can be declared within the function body with the ?local? keyword when they are assigned for first time. They are only accessible inside that function. We can create local variables with the same name in different functions. To add a local variable, we can use the following syntax: local var_name=_____________________________ To better understand how variables scope works in Bash Scripting, check out the following example: Bash Script #!/bin/bash____________________________________________ _______________________________________________________ v1='A'_________________________________________________ v2='B'_________________________________________________ ____________________________________________________________ my_var () {_________________________________________________ local v1='C'________________________________________________ v2='D'______________________________________________________ echo "Inside Function"______________________________________ echo "v1 is $v1."___________________________________________ echo "v2 is $v2."___________________________________________ }___________________________________________________________ ____________________________________________________________ echo "Before Executing the Function"________________________ echo "v1 is $v1."___________________________________________ echo "v2 is $v2."___________________________________________ ____________________________________________________________ my_var______________________________________________________ echo "After Executing the Function"_________________________ echo "v1 is $v1."___________________________________________ echo "v2 is $v2."___________________________________________ As per output, if we set a local variable within the function body with the same name as an existing global variable, then it will have precedence over the global variable. Global variables can be modified within the function. Return Values Most of the programming languages have the concept of returning a value for the functions. It means that the function has to send the data back to the original calling location. Unlike functions in 'real' programming languages, Bash function doesn't provide support to return a value when it is called. However, they allow us to set a return status which is similar to how a program or command exits with an exit status. When a bash function completes, its return value is the status of the last executed statement in the function. It returns 0 for the success status and non-zero decimal number in the 1-255 range for failure. The return status can be indicated by using the 'return' keyword, and it is assigned to the variable $?. The return statement terminates the function and works as the function's exit status. For example, consider the following code: Bash Script #!/bin/bash____________________________________________ #Setting up a return status for a function_____________ _______________________________________________________ print_it () {__________________________________________ echo Hello $1______________________________________________ return 5___________________________________________________ }___________________________________________________________ ____________________________________________________________ print_it User_______________________________________________ print_it Reader_____________________________________________ echo The previous function returned a value of $?___________ Another better option to return a value from a function is to send the value to stdout using echo or printf commands, as shown below: Bash Script #!/bin/bash____________________________________________ _______________________________________________________ print_it () {__________________________________________ local my_greet="Welcome to Javatpoint."_______________ echo "$my_greet"___________________________________________ }___________________________________________________________ ____________________________________________________________ my_greet="$(print_it)"______________________________________ echo $my_greet______________________________________________ Overriding Commands We have an option to override the bash commands by creating a function with the same name as the command that we are going to override. For example, if we want to override the 'echo' command, then we have to create a function with the name 'echo'. This concept of overriding the bash commands may be helpful in some scenarios like when we want to use a command with specific options. Also, when we do not like to provide the whole command with options for several times within the script. In such cases, we can override the in-built bash command for command with options. Now, let's understand the concept of overriding the commands in Bash Shell Scripting with the help of some examples: Example In this example, we have overridden the 'echo' command and added the time stamp in the form of the argument to the 'echo' command. Bash Script #!/bin/bash____________________________________________ #Script to override command using function_____________ _______________________________________________________ echo () {______________________________________________ builtin echo -n `date +"[%m-%d %H:%M:%S]"` ": "____________ builtin echo $1____________________________________________ }___________________________________________________________ ____________________________________________________________ echo "Welcome to Javatpoint."_______________________________ Bash Array ==================================================================================================== In this topic, we will demonstrate the basics of bash array and how they are used in bash shell scripting. An array can be defined as a collection of similar type of elements. Unlike most of the programming languages, arrays in bash scripting need not be the collection of similar elements. Since Bash does not discriminate the string from a number, an array may contain both strings and numbers. Bash does not provide support for the multidimensional arrays; we cannot have the elements which are arrays in themself. Bash provides support for one-dimensional numerically indexed arrays as well as associative arrays. To access the numerically indexed array from the last, we can use negative indices. The index of '-1' will be considered as a reference for the last element. We can use several elements in an array. Bash Array Declaration Arrays in Bash can be declared in the following ways: Creating Numerically Indexed Arrays We can use any variable as an indexed array without declaring it. To explicitly declare a variable as a Bash Array, use the keyword 'declare' and the syntax can be defined as: declare -a ARRAY_NAME__________________________________ where, ARRAY_NAME indicates the name that we would assign to the array. Note: Rules of naming a variable in Bash are the same for naming an array. A general method to create an indexed array can be defined in the following form: ARRAY_NAME[index_1]=value_1____________________________ ARRAY_NAME[index_2]=value_2____________________________ ARRAY_NAME[index_n]=value_n____________________________ where keyword 'index' is used to define positive integers. Creating Associative Arrays Unlike numerically indexed arrays, the associative arrays are firstly declared. We can use the keyword 'declare' and the -A (uppercase) option to declare the associative arrays. The syntax can be defined as: declare -A ARRAY_NAME__________________________________ A general method to create an associative array can be defined in the following form: declare -A ARRAY_NAME__________________________________ ARRAY_NAME[index_foo]=value_foo________________________ ARRAY_NAME[index_bar]=value_bar________________________ ARRAY_NAME[index_xyz]=value_xyz________________________ where index_ is used to define any string. We can also write the above form in the following way: declare -A ARRAY_NAME__________________________________ _______________________________________________________ ARRAY_NAME=(___________________________________________ [index_foo]=value_foo_________________________________ [index_bar]=value_bar______________________________________ [index_xyz]=value_xyz______________________________________ )___________________________________________________________ Bash Array Initialization To initialize a Bash Array, we can use assignment operator (=), by specifying the list of the elements within parentheses, separated by spaces like below: ARRAY_NAME=(element_1st element_2nd element_Nth)_______ Note: Here, the first element will have an index 0. Also, there should be no space around the assignment operator (=). Access Elements of Bash Array To access the elements of a Bash Array, we can use the following syntax: echo ${ARRAY_NAME[2]}__________________________________ Print Bash Array We can use the keyword 'declare' with a '-p' option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME__________________________________ Array Operations Once an array is assigned, we can perform some useful operations on it. We can display its keys and values as well as modify it by appending or removing the elements: Reference Elements To reference a single element, we are required to know the index number of the element. We can reference or print any element using the following syntax: ${ARRAY_NAME[index]}___________________________________ Note: Curly braces ${} are required to avoid shell's filename expansion operators. For example, let's print an element of an array with an index of 2: Bash Script #!/bin/bash____________________________________________ #Script to print an element of an array with an index o _______________________________________________________ #declaring the array___________________________________ declare -a example_array=( "Welcome""To""Javatpoint" )______ ____________________________________________________________ #printing the element with index of 2_______________________ echo ${example_array[2]}____________________________________ If we use @ or * in the place of a specified index, it will expand to all members of the array. To print all the elements, we can use the following form: Bash Script #!/bin/bash____________________________________________ #Script to print all the elements of the array_________ _______________________________________________________ #declaring the array___________________________________ declare -a example_array=( "Welcome""To""Javatpoint" )______ ____________________________________________________________ #Printing all the elements__________________________________ echo "${example_array[@]}"__________________________________ The only difference between using @ and * is that the form is surrounded with double quotes while using @. In the first case (while using @), the expansion provides a result in a word for each element of the array. It can be better described with the help of "for loop". Assume we have an array with three elements, "Welcome", "To" and "Javatpoint": $ example_array= (Welcome to Javatpoint)_______________ Applying a loop with @: for i in "${example_array[@]}"; do echo "$i"; done_____ It will produce the following result: Welcome To Javatpoint Applying a loop with *,a single result will be produced holding all the elements of the array as a single word: Welcome To Javatpoint It is important to understand the usage of @ and * because it is useful while using the form to iterate through array elements. Printing the Keys of an Array We can also retrieve and print the keys used in indexed or associative arrays, instead of their respective values. It can be performed by adding the ! operator before the array name as below: ${!ARRAY_NAME[index]}__________________________________ Example #!/bin/bash____________________________________________ #Script to print the keys of the array_________________ _______________________________________________________ #Declaring the Array___________________________________ declare -a example_array=( "Welcome""To""Javatpoint" )______ ____________________________________________________________ #Printing the Keys__________________________________________ echo "${!example_array[@]}"_________________________________ Finding Array Length We can count the number of elements contained in the array by using the following form: ${#ARRAY_NAME[@]}______________________________________ Example #!/bin/bash____________________________________________ _______________________________________________________ #Declaring the Array___________________________________ declare -a example_array=( "Welcome""To""Javatpoint" )_ ____________________________________________________________ #Printing Array Length______________________________________ echo "The array contains ${#example_array[@]} elements"_____ Loop through the Array The general method to iterate over each item in an array is by using the 'for loop'. Example #!/bin/bash____________________________________________ #Script to print all keys and values using loop through _______________________________________________________ declare -a example_array=( "Welcome""To""Javatpoint" )_ ____________________________________________________________ #Array Loop_________________________________________________ for i in "${!example_array[@]}"_____________________________ do__________________________________________________________ echo The key value of element "${example_array[$i]}" is_____ done________________________________________________________ Another common method to loop through an array is to retrieve the length of the array and use the C-style loop: Bash Script #!/bin/bash____________________________________________ #Script to loop through an array in C-style____________ _______________________________________________________ declare -a example_array=( "Welcome""To""Javatpoint" )_ ____________________________________________________________ #Length of the Array________________________________________ length=${#example_array[@]}_________________________________ ____________________________________________________________ #Array Loop_________________________________________________ for (( i=0; i < ${length}; i++ ))___________________________ do _________________________________________________________ echo $i ${example_array[$i]}________________________________ done________________________________________________________ Adding Elements to an Array We have an option to add elements to an indexed or associative array by specifying their index or associative key respectively. To add the new element to an array in bash, we can use the following form: ARRAY_NAME[index_n]="New Element"______________________ Example #!/bin/bash____________________________________________ _______________________________________________________ #Declaring an array____________________________________ declare -a example_array=( "Java""Python""PHP""HTML" )_ ____________________________________________________________ #Adding new element_________________________________________ example_array[4]="JavaScript"_______________________________ ____________________________________________________________ #Printing all the elements__________________________________ echo "${example_array[@]}"__________________________________ Output Java Python PHP HTML JavaScript Another method for adding a new element to an array is by using the += operator. There is no need to specify the index in this method. We can add one or multiple elements in the array by using the following way: Example #!/bin/bash____________________________________________ _______________________________________________________ #Declaring the Array___________________________________ declare -a example_array=( "Java""Python""PHP" )_______ ____________________________________________________________ #Adding new elements________________________________________ example_array+=( JavaScript CSS SQL )_______________________ ____________________________________________________________ #Printing all the elements__________________________________ echo "${example_array[@]}"__________________________________ Output Java Python PHP JavaScript CSS SQL Updating Array Element We can update the array element by assigning a new value to the existing array by its index value. Let's change the array element at index 4 with an element 'Javatpoint'. Example #!/bin/bash____________________________________________ #Script to update array element________________________ _______________________________________________________ #Declaring the array___________________________________ declare -a example_array=( "We""welcome""you""on""SSSIT_____ ____________________________________________________________ #Updating the Array Element_________________________________ example_array[4]=Javatpoint_________________________________ ____________________________________________________________ #Printig all the elements of the Array______________________ echo ${example_array[@]}____________________________________ Output We welcome you on Javatpoint Deleting an Element from an Array If we want to delete the element from the array, we have to know its index or key in case of an associative array. An element can be removed by using the 'unset' command: unset ARRAY_NAME[index]________________________________ An example is shown below to provide you a better understanding of this concept: Example #!/bin/bash____________________________________________ #Script to delete the element from the array___________ _______________________________________________________ #Declaring the array___________________________________ declare -a example_array=( "Java""Python""HTML""CSS""Ja_____ ____________________________________________________________ #Removing the element_______________________________________ unset example_array[1]______________________________________ ____________________________________________________________ #Printing all the elements after deletion___________________ echo "${example_array[@]}"__________________________________ Output Java HTML CSS JavaScript Here, we have created a simple array consisting of five elements, "Java", "Python", "HTML", "CSS" and "JavaScript". Then we removed the element "Python" from the array by using "unset" and referencing the index of it. The index of element "Python" was '1', since bash arrays start from 0. If we check the indexes of the array after removing the element, we can see that the index for the removed element is missing. We can check the indexes by adding the following command into the script: echo ${!example_array[@]}______________________________ The output will look like: 0 2 3 4 This concept also works for the associative arrays. Deleting the Entire Array Deleting an entire array is a very simple task. It can be performed by passing the array name as an argument to the 'unset' command without specifying the index or key. Example #!/bin/bash____________________________________________ #Script to delete the entire Array_____________________ _______________________________________________________ #Declaring the Array___________________________________ declare -a example_array=( "Java""Python""HTML""CSS""Ja_____ ____________________________________________________________ #Deleting Entire Array______________________________________ unset example_array_________________________________________ ____________________________________________________________ #Printing the Array Elements________________________________ echo ${!example_array[@]}___________________________________ ____________________________________________________________ #Printing the keys__________________________________________ echo ${!example_array[@]}___________________________________ Output Bash Array There will be no output if we try to print the content of the above script. An empty result is returned because the array doesn't exist anymore. Slice Array Elements Bash arrays can also be sliced from a given starting index to the ending index. To slice an array from starting index 'm' to an ending index 'n', we can use the following syntax: SLICED_ARRAY=(${ARRAY_NAME[@]:m:n}")___________________ Example #!/bin/bash____________________________________________ #Script to slice Array Element from index 1 to index 3_ _______________________________________________________ #Declaring the Array___________________________________ example_array=( "Java""Python""HTML""CSS""JavaScript" )_____ ____________________________________________________________ #Slicing the Array _________________________________________ sliced_array=("${example_array[@]:1:3}")____________________ ____________________________________________________________ #Applying for loop to iterate over each element in Arra_____ for i in "${sliced_array[@]}"_______________________________ do__________________________________________________________ echo $i_____________________________________________________ done________________________________________________________ Output Bash Array 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. value=`cat file_name`__________________________________ Example #!/bin/bash____________________________________________ _______________________________________________________ value=`cat read_file.txt`______________________________ echo "$value"__________________________________________ Reading File Using '$() Following is the syntax to read the content of the file using '$' value=$(file_name)_____________________________________ Example #!/bin/bash____________________________________________ _______________________________________________________ value=$() or double right-angle sign (>>): Right Angle Bracket Sign (>) It is used to write the output of bash command to a disk file. If there is no file with the specified name, then it creates a new file with the same name. If the file is there with the specified name, then the content of the file will be overwritten. Double Right Angle Sign (>>) It is used to write the output of bash commands to a file, appending the output to the existing contents of the file. If the file is not present, it creates a new one with the specified name. Technically, both of these operators redirect "stdout (the standard output)" to a file. In a simple way, when we are writing the file for the first time and do not want previous data to be present in the file, we should use the right angle bracket sign (>). It will overwrite the content if it is already present in the file. And in the further script, we may use double right-angle sign (>>) to append the data to a file. Example The 'ls' command is used to print all the files and folders present in the current directory. But when we run the 'ls' command with a right angle bracket sign (>), it will not print the list of files and folders to the screen. It will save the output to the file that we specify with it, i.e., as shown below: Bash Script #!/bin/bash____________________________________________ #Script to write the output into a file________________ _______________________________________________________ #Create output file, override if already present_______ output=output_file.txt______________________________________ ____________________________________________________________ #Write data to a file_______________________________________ ls > $output________________________________________________ ____________________________________________________________ #Checking the content of the file___________________________ gedit output_file.txt_______________________________________ As shown here, the output of 'ls' command is redirected into a file. To print the contents of a file to the terminal, we can use the 'cat' command in the following form: Bash Script #!/bin/bash____________________________________________ #Script to write the output into a file________________ _______________________________________________________ #Create output file, override if already present_______ output=output_file.txt______________________________________ ____________________________________________________________ #Write data to a file_______________________________________ ls > $output________________________________________________ ____________________________________________________________ #Printing the content of the file___________________________ cat $output_________________________________________________ If we want to redirect the output of multiple commands to a single file without deleting the available data, then we can use the >> operator. Suppose we want to append the system information to the specified file, we can do that in the following way: Bash Script #!/bin/bash____________________________________________ #Script to write the output into a file________________ _______________________________________________________ #Create output file, override if already present_______ output=output_file.txt______________________________________ ____________________________________________________________ #Write data to a file_______________________________________ ls > $output________________________________________________ ____________________________________________________________ #Appending the system information___________________________ uname -a >> $output_________________________________________ ____________________________________________________________ #Checking the content of the file___________________________ gedit output_file.txt_______________________________________ Here, the result of the second command is appended to the end of the file. We can repeat this process several times to keep appending the output to the end of the file. Method 2: Print Output Normally and Write it to a File Some people may not like writing output to a file using > or >> operators, as there will be no output of the command in the terminal. That is why the 'tee' command is used. The 'tee' command is used to print the input that it receives to the screen. It can save the output to a file at the same time. Bash Script #!/bin/bash____________________________________________ #Script to write the output into a file________________ _______________________________________________________ #Create output file, override if already present_______ output=output_file.txt______________________________________ ____________________________________________________________ #Write data to a file_______________________________________ ls | tee $output____________________________________________ This will override the content of the file, just like the > operator but also print the output on the screen. If we want to write the output to a file without removing the contents of the file using tee command, we can use the following form which will also print the output to the terminal: Bash Script #!/bin/bash____________________________________________ #Script to write the output into a file________________ _______________________________________________________ #Create output file, override if already present_______ output=output_file.txt______________________________________ ____________________________________________________________ echo "<<>>" | tee -a $output_____ #Write data to a file_______________________________________ ls | tee $output____________________________________________ ____________________________________________________________ echo | tee -a $output_______________________________________ #Append System Information to the file______________________ echo "<<>>" | tee -a $output_______________________ uname | tee -a $output______________________________________ This will not only append the output to the end of the file but also print the output on the screen. Bash check if file Exists ==================================================================================================== Most of the time, we may find a situation where we may need to perform an action that will check whether a file exists or not. In Bash, we can use a 'test command' to check whether a file exists and determine the type of a file. Following are the syntaxes of the test command, and we can use any of these commands: test expression________________________________________ [ expression ]_________________________________________ [[ expression ]]_______________________________________ We are required to use a single bracket '[' command to make our script portable for all POSIX shells. The upgraded version of the test command contains double brackets '[[' which is supported on most of the modern systems using Bash, Zsh, and Ksh as a default shell. Check If File Exists While checking if a file exists, the most commonly used file operators are -e and -f. The '-e' option is used to check whether a file exists regardless of the type, while the '-f' option is used to return true value only if the file is a regular file (not a directory or a device). The most common option to check if the file exists or not is to use the test command with the 'if conditional statement'. Following are the examples to check whether the 'read_file.txt' file exists: Method 1 #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ if test -f "$File"; then_______________________________ echo "$File exist "_________________________________________ fi__________________________________________________________ Method 2 #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ if [ -f "$File" ]; then________________________________ echo "$File exist "_________________________________________ fi__________________________________________________________ Method 3 #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ if [[ -f "$File" ]]; then______________________________ echo "$File exist "_________________________________________ fi__________________________________________________________ If we want to perform an action which will provide a result based on whether the file exists or not, we can use the if/then construct in the following way: Example #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ if [ -f "$File" ]; then________________________________ echo "$File exist"__________________________________________ else________________________________________________________ echo "$File does not exist"_________________________________ fi__________________________________________________________ We can also use the test command without the if statement. We can use any of the following methods: Method 1 #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ test -f read_file.txt && echo "$File exist"____________ Method 2 #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ [ -f read_file.txt ] && echo "$File exist"_____________ Method 3 #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ [[ -f read_file.txt ]] && echo "$File exist"___________ If there are several commands to be run after the && operator, then enclose the commands in curly brackets separated by semicolon(;) or AND (&&), i.e.: Example #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ [ -f read_file.txt ] && { echo "$File exist"; echo "Tas Unlike &&, the statement after the || operator is executed only if the exit status of the test command is 'false'. Example #!/bin/bash____________________________________________ _______________________________________________________ File=read_file.txt_____________________________________ _______________________________________________________ [ -f read_file.txt ] && echo "$File exist" || echo "$Fi_____ These are the commonly used methods in Bash to check whether the file exists or not. Check If Directory Exists The operator '-d' allows us to test whether a file is a directory or not. Following are the methods to check whether the 'Javatpoint' directory exists: Method 1 #!/bin/bash____________________________________________ _______________________________________________________ File=Javatpoint________________________________________ if [ -d "$File" ]; then________________________________ echo "$File is a directory"_________________________________ fi__________________________________________________________ Method 2 #!/bin/bash____________________________________________ _______________________________________________________ File=Javatpoint________________________________________ [ -d "$File" ] && echo "$File is a directory"__________ Note: We can also use double brackets '[[' instead of a single bracket '['. Check IF File does not Exist The test expression can be negated by using the exclamation mark (! -logical NOT operator). Check out the following example: Example #!/bin/bash____________________________________________ _______________________________________________________ File=missing_read_file.txt_____________________________ if [ ! -f "$File" ]; then______________________________ echo "$File does not exist"_________________________________ fi__________________________________________________________ Above script can also be written as below: #!/bin/bash____________________________________________ _______________________________________________________ File=missing_read_file.txt_____________________________ [ ! -f "$File" ] && echo "$File unavailable"___________ File Test Operators The test commands include the following File Operators which allow us to test for particular types of files: -b File Returns 'True' if the FILE exists as a block special file. -c File Returns 'True' if the FILE exists as a special character file. -d File Returns 'True' if the FILE exists as a directory. -e File Returns 'True' if the FILE exists as a file, regardless of type (node, directory, socket, etc.). -f File Returns 'True' if the FILE exists as a regular file (not a directory or device). -G File Returns 'True' if the FILE exists and contains the same group as the user is running the command. -h File Returns 'True' if the FILE exists as a symbolic link. -g File Returns 'True' if the FILE exists and contains set-group-id (sgid) flag set. -k File Returns 'True' if the FILE exists and contains a sticky bit flag set. -L File Returns 'True' if the FILE exists as a symbolic link. -O File Returns 'True' if the FILE exists and is owned by the user who is running the command. -p File Returns 'True' if the FILE exists as a pipe. -r File Returns 'True' if the FILE exists as a readable file. -S File Returns 'True' if the FILE exists as a socket. -s File Returns 'True' if the FILE exists and has nonzero size. -u File Returns 'True' if the FILE exists, and set-user-id (suid) flag is set. -w File Returns 'True' if the FILE exists as a writable file. -x File Returns 'True' if the FILE exists as an executable file. Bash Check if Variable is Set ==================================================================================================== A variable is often referred to as a box containing a name and the contents. A simple command, e.g., "echo Hello $Var_Name' will print "Hello...the value of the variable as defined'. Bash will print nothing if the box is empty or not created. That is why it is important to make sure whether a variable is set properly or not while creating any bash script. Variables can be categorized into two parts: * Defined Variables Variables which are properly created or initialized, are known as Defined Variables. These may have zero value or an empty string. * Undefined Variables Variables which are never created or initialized, are known as Undefined Variables. To confirm whether a variable is set or not in Bash Scripting, we can use -v var or -z ${var} options as an expression with the combination of 'if' conditional command. Syntax Following are the syntaxes of boolean expression which can be used to check if the variable is set: [[ -v Variable_Name ]]_________________________________ _______________________________________________________ [[ -z Variable_Name ]]_________________________________ The boolean expression returns 'True' if the variable is set and 'False' if the variable is not set. Following are the examples to check whether a variable is set or not: Using -v Option #!/bin/bash____________________________________________ #Script to check whether a variable is set or not using _______________________________________________________ A=100__________________________________________________ #A: variable is set.________________________________________ ____________________________________________________________ if [[ -v A ]];______________________________________________ then________________________________________________________ echo "Variable having name 'A' is already set."_____________ else________________________________________________________ echo "Variable having name 'A' is not set."_________________ fi__________________________________________________________ ____________________________________________________________ #B: variable is not set_____________________________________ if [[ -v B ]];______________________________________________ then________________________________________________________ echo "Variable having name 'B' is already set."_____________ else________________________________________________________ echo "Variable having name 'B' is not set."_________________ fi__________________________________________________________ Here, variable 'A' is defined and assigned a value of 100 and hence is considered as 'set variable'. For variable 'B', we have not defined or assigned any value. As a result, the variable 'B' is not considered as 'set variable'. Using -z Option #!/bin/bash____________________________________________ #Script to check whether a variable is set or not using _______________________________________________________ A=100__________________________________________________ #A: variable is set.________________________________________ if [[ -z ${A} ]];___________________________________________ then________________________________________________________ echo "Variable having name 'A' is not set."_________________ else________________________________________________________ echo "Variable having name 'A' is already set."_____________ fi__________________________________________________________ ____________________________________________________________ #B: variable is not set_____________________________________ if [[ -z ${B} ]];___________________________________________ then________________________________________________________ echo "Variable having name 'B' is not set."_________________ else________________________________________________________ echo "Variable having name 'B' is already set."_____________ fi__________________________________________________________ Note: There is a difference between an unset variable and a variable with a null value. Check out the following example demonstrating that the variable with a null value can be a set variable. Example VAR=''_________________________________________________ _______________________________________________________ #VAR is set____________________________________________ _______________________________________________________ if [ -z ${VAR+x} ]; ________________________________________ then _______________________________________________________ echo "'VAR' is unset"; _____________________________________ else _______________________________________________________ echo "'VAR' is set, its content is '$VAR'"; ________________ fi__________________________________________________________ ____________________________________________________________ #Var is not set_____________________________________________ if [ -z ${Var+x} ]; ________________________________________ then _______________________________________________________ echo "'Var' is unset"; _____________________________________ else _______________________________________________________ echo "'Var' is set, its content is '$Var'"; ________________ fi__________________________________________________________ These are the commonly used methods that can be used to check if a variable is set or not. Bash Alias ==================================================================================================== There are the majority of commands that we use while operating the command-line interface. Most of the commands are habitual, and people may run those commands in the same way every day. However, we have an option in Bash to create our own shortcuts with the help of aliases, which will eliminate the extraneous typing by using shortened names. Bash Alias is used to set a shortcut command for a longer command. The alias command allows us to launch any command or set commands by using a single word. For example, we can set the command 'cc' as a shortcut for the 'clear' command. Using 'cc + enter' is comparatively much faster than to type 'clear' command. Alias is usually declared within the ~/.bash_profile or ~/.bashrc file. "A .bash_profile and .bashrc files are referred to as configuration files for the bash shell. All the bash configurations, such as all the terminal sessions, the configuration comprising of environment variables, default directory, color, bash theme, etc., are stored in the configuration file. The name of the configuration file is usually ".bashrc" for a terminal-sessions and ".bash_profile" for login shells." Bash Alias Structure A bash alias contains the following structure: alias [alias_name]="[command_to_alias]"________________ A new alias is defined on a new line with the 'alias' keyword. We need to define the shortcut command that we want to use with the alias name, followed by an equal sign. Then, we type the full command that we want to run within the quotes. There should be no spacing between the neighbor elements and the equal sign. It's an important thing to remember; otherwise, the command will be broken. Create a Bash Alias Creating aliases in bash is straight forward. We can declare the aliases into the command line by following the structure shown above. Let's start with a simple bash alias now. One of the commonly used commands that many people use to get the listing of all the files and directory, including hidden files, is "ls -la". We can create a shortcut "ll' to perform an action of "ls -la" by typing the following command in a terminal: alias ll="ls -la"______________________________________ Now, if we type the alias "ll" in a terminal, we will receive the listing of all the files and directories in a long format as similar to the "ls -la" command. Bash Alias Note: It should be noted that if we set the aliases through a terminal using this way, aliases will only be available for the current shell session. When we open a new terminal window, aliases will not be available. If we want to make the defined aliases persistent, we have to add this into one of the files which are read when a shell session starts. The most common choices are ~/.bash_profile or ~/.bashrc, as we have mentioned earlier. We are required to open any of these files and add the aliases there. Bash Alias It is a good practice to assign such names for the aliases, which are easy to remember. It is also suggested to add a comment declaring an entire function related to bash aliases for future reference. If we want to make our .bashrc file more modular, then we can put the aliases in a separate file, i.e., ~/.bash_aliases. We need to make sure that the code appears in the ~/.bashrc file: if [ -e $HOME/.bash_aliases ]; then____________________ source $HOME/.bash_aliases_____________________________ fi_____________________________________________________ Remove/Delete a Bash Alias To remove the alias, we are required to use the following structure: unalias [alias_name]="[command_to_alias]"______________ To remove the "ll" alias that we have created above, we can use the unalias command: unalias ll_____________________________________________ Bash Alias The "ll" alias will be removed. If aliases are declared in ~/.bash_profile or ~/.bashrc, simply edit the file using a text editor and remove those aliases from there. List Bash Aliases We can list all the configured aliases by using the "alias" command in a terminal without any arguments: alias__________________________________________________ Bash Aliases with Arguments (Bash Functions) In some cases, we may require the aliases which accept one or more argument. In such cases, bash functions are useful. Following is the syntax for creating bash functions. It can be declared in two different formats: function_name () {____________________________________ [commands]____________________________________________ }______________________________________________________ Or function function_name {_______________________________ [commands]____________________________________________ }______________________________________________________ To pass any number of arguments to the bash function, we can simply put them right after the function's name separated by a space. The passed parameters can be $1, $2, $3, etc. It usually depends upon the corresponding position of the parameter after the function's name. The $0 variable is kept reserved for the function name. Now, we are going to create a simple bash function, which will create a directory and then navigate into it without using 'mkdir' and 'cd' command: mkcd ()________________________________________________ {______________________________________________________ mkdir -p -- "$1" && cd -p -- "$1"______________________ }______________________________________________________ Just like aliases, we need to add the function to the ~/.bashrc file and run source~/.bash_profile to reload the file. Here, AND Operator (&&) ensures that the second command runs only if the first command is executed successfully. And double dash sign (--) ensures that we are not passing an extra argument to the command. Now, we can create a new directory and then move into that directory using the command: mkcd new_directory_____________________________________ Hence, the aliases are an excellent alternative to reduce the amount of typing for the long commands repeatedly. Git Bash ==================================================================================================== Git can be defined as a set of command-line utility programs designed to execute on a Windows environment. Many operating systems such as Linux and macOS contain built-in UNIX command line terminals. It makes Linux and macOS complementary operating systems when working with Git. Windows do not have the UNIX style command interface. Instead, Microsoft Windows use windows command prompt, a non- UNIX terminal. Hence, Git for Windows provides a Bash emulation to run Git from the command line. In other words, Git Bash is an application that adds an emulation layer on Microsoft Windows environments to use Git command-line experience. It is just like a package that installs some common bash utilities on a Windows operating system. It let us use all the Git features as well as most of the standard UNIX commands in a command-line interface on Windows. How to install Git Bash Git Bash is included with the 'Git For Windows' package. Download the latest version of the Git Bash package from the official website and install it just like the other Windows applications. Following is the link to download 'Git for Windows': Download Link: [171]Click Here Git Bash Once the package is downloaded, run the executable file: Git Bash Choose the valid path where you want to install the Git Bash: Git Bash Select the appropriate componenets you want to install and hit 'next' button: Git Bash Follow the next on screen instructions to finish the installation. To check the version of Git for Windows, use the command: git --version__________________________________________ After running this command, the output will look like this: Git Bash Launch Git Bash After the installation is completed, search for the icon named 'Git Bash' and double click on it to start the Git Bash. It will start a 'bash shell' integrated with Git. Git Bash Git Bash works as similar as a standard bash and is useful to review basic Bash usage. It includes the complete set of Git core commands. It is also packaged with additional commands which can be found in the /usr/bin directory of the Git Bash emulation. This is how we can use Bash Shell Scripting on Windows operating system. Zsh Vs. Bash ==================================================================================================== Zsh shell is one of the most popular shells. It is also known as the "Z shell". Although the bash shell and Zsh shell both are known as the powerful shells, they also have requirements according to the preferences that users may have. Since both the shells are under active development, it is not sensible to be too specific here. Some of the important differences between Zsh and Bash are given below: Zsh Bash Zsh provides advanced tab-completion features which are much faster and smarter (supports case insensitive completion with smart defaults). Bash lacks some completion features comparatively to Zsh and is not as fast as Zsh. Zsh is not installed by default in most of the Linux/UNIX machines. Bash is a built-in shell in most of the Linux/UNIX machines, which makes it portable across different systems. Zsh supports recursive path expansion. It means if there is only one path (let's assume: /usr/local/bin), then we can type "cd /u/l/b" and press the tab button to access that path. Bash does not provide support for recursive path expansion. However, there are some alternative ways like using vim or command completion (compgen -c). Zsh has built-in spelling correction and approximate completion feature for the typing mistakes in directory names or command names. Bash does not support spelling correction and completion features by default. Zsh provides supports for several plugin frameworks and themes. Bash has limited support for the plugin frameworks and themes. In Zsh, 'which command' will reveal the definition of an alias, the source for a function, and the location of a command. In Bash, 'which command' only reveals the location of a command. This is how we can differentiate Zsh and Bash. Bash Hash Command ==================================================================================================== On UNIX-like operating systems, a hash is a built-in command of the bash shell, which is used to list a hash table of recently executed commands. It is used for views, resets, or manually changes within the bash path hash. It keeps the locations of recently executed programs and shows them whenever we want to see it. It provides a complete pathname of each command name. In other words, when any command is executed without naming its path, the shell starts searching for that command within the directories, which are listed in the path variable. When the Bash gets that command, it keeps the location in a hash table so that it can remember the location of the command. After that, Bash starts checking the table to find the location of the command instead of looking for the command again. It makes the command run faster. However, if the command is moved after recording its location in a table, the shell will not be able to find the command. In this case, a full search of the directories in the path is performed to get the command data. The built-in 'hash' command is responsible for maintaining the hash table. Without any switches, hash lists the previously used commands, their locations, and the number of times they have been executed during the session. Syntax hash [-l] [-r] [-p pathname] [-d] [-t] [command_name . The syntax above is used to determine and remember the full pathname of each command_name. If there are no arguments, it displays the information about previously used commands and their locations. Options -d Forget the remembered locations of command_name. -l Display the information that can be used again as an input for another program. -p Use pathname as the full path of command_name. -r Forget all the remembered locations. -t Print the remembered location of each command_name. If multiple command_names are given there, precede each location with corresponding command_name command_name Each command_name specified is searched for in the path environment variable, and if found, is added to the list of remembered commands. Exit Status The hash command returns '0' for success. Value other than zero refers that the command_name is not found, or an invalid option is given. Listing Bash Hash Table We can display the hash table for the current session by invoking hash without any argument. hash___________________________________________________ Here, the hash command displays the number of hits (calls for that command) and the command with its path during the session. The sum of all the hits is considered as the number of saved searches through the path. Note- If a new session is opened where no command has been executed, then there will be no hash table for that session. The output will look like this: Hash Command If we use the -l option, then it will display a hash table in a format that can be used as an input, i.e., hash -l________________________________________________ We can also print the remembered locations of commands which are used during the session by using the -t option. Hash Command We can also print the locations of multiple commands separated by spaces, i.e., Hash Command Adding a Command Path and Name to the Bash Hash Table We can add items to the hash table that can be used again in the shell. It should be remembered that the hash table only exists in the current live session of the shell. If we open a new shell, the bash will create a new hash table according to the executed commands of that shell. As soon as we start running the first command, bash starts creating a hash table. To add a command to the hash table, we can use the -p option followed by the path and then the name. In this way, we can use the hash table as similar to an alias. Following is an example where we have added the /home/bash.sh script to the hash table with the name 'bash'. Hash Command After adding the /home/bash.sh to the hash table with a mapped name 'bash', we can directly invoke it by the name 'bash': Hash Command Bash checks the hash table for the command name to find the executable. Generally, there is no need to put the script in the path unless we want it to be available in a new shell. Deleting an Item from the Hash Table We also have an option to delete or forget a remembered location of commands in hash bash. We can simply use the -d option followed by the name to perform this task: Hash Command Here, we have deleted the /home/bash.sh from the hash table, which was mapped with a name 'bash'. Clearing the Hash Table To clear the hash table, we can use the -r option. Hash Command Here, it can be seen that the hash table is cleared successfully by using the -r option.