Single Line if...else in Bash
Conditional statements are the basic part of any program that decides to depend on various conditions. In this article, we will learn about the
if ... else conditional statement and how we can create a single line
if ... else statement.
Also, we will see necessary examples and explanations to make the topic easier.
As we know, the general syntax for the
if ... else in Bash is:
if [ YOUR_CONDITION_HERE ] then // Block of code when the condition matches else // Default block of code fi
Now before we go to the single-line format of an
if ... else statement, we need to understand the multiline format of this conditional statement.
a Multiline Example for
if ... else in Bash
Our example below will check whether a value is greater than 15. For this purpose, we will use an
if ... else statement and the multiline format.
Now, the code for our example will look like this:
num=10 if [ $num -gt 15 ] then echo "The provided value is greater than 15" else echo "The provided value is less than 15" fi
You will get the below output after you run the example code.
The provided value is less than 15
Remember the code
-gt means greater than.
a Single Line Example for
if ... else in Bash
Now we are going to see the single-line version of the above example. This example will provide similar output, but the code structure will be a single line.
A similar code will look like the one below.
num=16 if [ $num -gt 15 ]; then echo "The value is greater than 15"; else echo "The value is less than 15"; fi
The only thing you must do here is to include a symbol
;. So from the above example, we can easily find that the general syntax for the single line
if ... else is something like:
if [ YOUR_CONDTION_HERE ]; then # Block of code when the condition matches; else # Default block of code; fi
You will get the below example after you run the example code.
The value is greater than 15
Writing it on a single line is very difficult when working with the nested
if ... else or complex conditions. And there is the highest chance of getting an error.
Besides, it will be difficult to find errors and bugs in your code if you use the single line
if ... else.
All the codes in this article are written in Bash. It will only be runnable in the Linux Shell environment.
Related Article - Bash Condition
- Multiple if Conditions in Bash Script
- Conditional Expressions in the Bash Shell
- The if Not Condition in Bash
- Use and With the if Statement in Bash