Bash If-Else Condition in One-Line [2 Ways]

In the traditional approach of using if-else structures, you had to write a bunch of lines of code to execute a single command. That’s why it’s so important to wrap if-else condition in one line of code, making them more portable. The syntax is:

if [ conditions ]; then command1; else command2; fi

Apart from that, Bash provides two distinct methods for composing if-else conditional statements, involving the use of a test command, and a ternary operator.

In this article, I will show how you can use an if-else condition in a one-line statement in Bash.

Convert Multiline if-else to One-line if-else

Writing statements in a single line over multiline if-else statements enhances productivity, facilitates portability, and is convenient. For instance, If you want to figure out if a certain number is bigger than another using the traditional if-else structure, you need to write multiple lines. On the contrary, you’ll be surprised to know that you can put all the conditional statements together in just one line.

Check out the following two examples to see how the traditional multiline if-else condition can be converted to a one-line code:

#!/bin/bash
number1=5
number2=4
if [ number1 -gt number2 ];
then
echo "number1 is greater than number2"
else
echo "number1 is not greater than number2"
fi

One-line structure:

if [ number1 -gt number2 ] && echo "number1 is greater than number2" || echo "number1 is not greater than number2"

You can see the code becomes handy once the multi-line structure is converted to a single line.

2 Ways to Write Bash If-Else Condition in One-Line

To write an if-else condition in one line, you can use the test command and ternary operator. You can also use parenthesis enclosing the statements to execute them in a subshell which allows scriptwriters to make their scripts faster and easier to read.

In this section, I will discuss 2 methods of how to express if-else conditions in one line:

1. Using “test” Commad

The test command checks the condition whether it is true or false and executes statements. To execute all the statements using a one-line code, use the if statement followed by a semicolon (;) to separate commands. Here’s an example checking whether the strings are equal or not using if-else in one line structure:

#!/bin/bash

if test "linuxsimply" == "linuxsimply"; then echo "strings are equal"; else echo "strings are different"; fi
EXPLANATION

The if statement initiates the condition check, using the test command to evaluate equality between the two strings. If the strings are indeed equal, it executes the code block following then, which prints “strings are equal” to the console. If the comparison returns false, the script executes the code block following else, which prints “strings are different”..

writing bash if else condition in one line using test command In this image, you can see that “strings are equal” as the condition is true.

NOTE: You can check multiple conditions in one line if conditions, connect the conditions with -a:

if test condition1 -a condition2 -a condition3; then action1; else action2

2. Using Ternary Operator

To express one-line if-else conditions in Bash, use the ternary operator AND “&&” and OR “||”. If the condition is true, the code associated with the AND operator will be executed, otherwise, the OR operator code block will be executed. Here’s an example to check the readability of file.txt using on-line if-else statements:

#!/bin/bash

file="/home/mou/file.txt"
[ -r "$file" ] && echo "The file is readable." || echo "The file is not readable."
EXPLANATION

Here, the script executes the statement after && “The file is readable.” when the condition is true. The statement after || “The file is not readable.” is executed if the condition is false.

writing bash if else condition in one line using ternary operator

As you can see in this image the script executes “The file is readable.” since the condition is true.

NOTE: You can also use parenthesis here to execute it in a subshell:

([ -r "$file" ] && echo "The file is readable.") || (echo "The file is not readable.")

Conclusion

To conclude, I have discussed the benefits of writing code in one line over multiline if-else structures. Additionally, I have demonstrated two methods for condensing bash if-else statements into one line. By mastering this skill, you can become proficient in bash scripting and write more straightforward codes. Best of luck!

People Also Ask

How do you write if else in one line?

To write if-else in one line, use ternary operators && and || to combine statements:

[ "$condition" = true ] && command_if_true || command_if_false

When the condition is true, it will execute the command after && operator. On the other hand, it will execute the command after the || operator.

How to check if a file exists in one line in bash?

You can use the -e flag and ternary operators && and || to check the existence of a file in one line code. Here’s an example:

[ -e "/path/to/your/file.txt" ] && echo "File exists" || echo "File does not exist"

If the file.txt exists, it returns the AND block code “File exists”, otherwise, it returns the code after the OR operator “File does not exist”.

Can I write multiple conditions in one line in bash?

Yes, you can write multiple conditions in one line in Bash using logical operators to combine them. Here’s an example using the logical AND && and logical OR || operators:

[ condition1 ] && [ condition2 ] && echo "Both conditions are true" || echo "At least one condition is false"

If both conditions are true, it will print the statement after && operator. When at least one condition is false, it will print the statement after the || operator.

How to use elif in a bash script?

The bash elif statement enables the execution of a sequence of instructions based on a collection of conditions. Check the syntax:

#!/bin/bash
if [ condition1 ]; then
# Code to be executed if condition1 is true
elif [ condition2 ]; then
# Code to be executed if condition2 is true
else
# Code to be executed if all conditions are false
fi

If condition1 is true, it executes the if block code. If the condition2 is true, the elif block code is executed. When none of the conditions are true, it executes the code assigned to the else block.

Can I use the ternary operator for complex conditions?

No, the ternary operator is appropriate for simple conditions, however, for more complex logic, it is recommended to utilize a more explicit multiline if-else operator to ensure readability.

What’s the difference between the logical AND (&&) and logical OR (||) operators in the ternary operator?

The logical AND && is used for the command following it if the condition is true, while the logical OR || is used for the command following it if the condition is false.

Are there any potential pitfalls with using one-liner if-else statements?

One of the pitfalls is that over-complicated one-liners can be difficult to read. Try to keep your one-liners short and clear, and opt for a more straightforward approach to complex logic. Another drawback is the heavy reliance on the writer’s skills.

Related Articles


<< Go Back to If Else in Bash | Bash Conditional Statements | Bash Scripting Tutorial

4.8/5 - (6 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Mitu Akter Mou

Hello, This is Mitu Akter Mou, currently working as a Linux Content Developer Executive at SOFTEKO for the Linuxsimply project. I hold a bachelor's degree in Biomedical Engineering from Khulna University of Engineering & Technology (KUET). Experiencing new stuff and gathering insights from them seems very happening to me. My goal here is to simplify the life of Linux users by making creative articles, blogs, and video content for all of them. Read Full Bio

Leave a Comment