Yahoo
Skip to main content
Advertisement
Advertisement
Advertisement
Advertisement

Learning this one feature means covering a huge chunk of Bash's capabilities.

Tux, the Linux mascot, wearing sunglasses and peeking from behind a large terminal window displaying globbing commands.
Lucas Gouveia/How-To Geek

Are you pondering learning how to script on Linux? Perhaps you wanted to create a service or automate something, but thought Bash was too much. The if-statement represents a huge chunk of how a script functions, yet you can learn it in an hour. That knowledge opens up many new, strong options on Linux, so it's worth taking the time to learn.

To learn Bash competently, you need only a few essential things, and they will carry you a very long way. Variables , functions , argument parsing , and if-statements. These are the foundational pillars, and today, I'll cover the latter.

What is an if-statement in Bash?

A means to handle questions and direct program flow

Advertisement
Advertisement

Simply put, it's a means to answer a question. Scripts make decisions, and the path through them gets determined by handling those questions. Each fork in the road is called a branch, and the questions themselves are conditions.

Let's jump right in and look at a simple example:

  • "==" is a comparison operator (is equal to)

  • A == Bis a condition (question)

  • "echo" psrints a message when the condition is true

  • "fi" ends the if-statement

This entire statement compares two values (which evaluates to true), then displays a message.

Notice how numbers and words (aka strings) have different bracket types? Parentheses (like((...))) are for numbers;[[ ... ]]is typically not (more on that next).

Creating conditions

Put questions inside double brackets

"1 == 1" is called an expression—which means it evaluates to a value. For example,1 + 1evaluates to2, and1 == 1totrue.

Advertisement
Advertisement

There are several ways to create expressions in Bash, and for if-statements, we most often use comparison operators (like "==" or ">"). Here are some concrete examples.

In Bash, conditions evaluate to a number (aka exit status ): "0" istrueand non-zero isfalse. I will usetrueandfalseto make things clear.

Parentheses ((( ... ))) and square brackets ([[ ... ]]) treat comparison operators differently:

  • For square brackets: Use-eq,-gt,-lt,-ge, and-leto compare numbers. Use==,>, andto compare strings.

  • For parentheses: use==,>,, , and >= to compare numbers. Never compare strings.

When comparing the letter forms (e.g.,-gt) to the symbols used in the parentheses notation (e.g.,(( a > b ))), this is what they mean:

A terminal window checks whether ten is greater than or equal to ten using both bracket notations. Each comparison returns an exit status of zero, meaning true.

These are the three valid ways to use them with the double-bracket notation:

Creating multiple conditions

Use logical operators to chain conditions

Inside the brackets you can use logical operatorsto evaluate multiple conditions:

"&&" and "||" work like their English labels: "and" and "or." For example, one equals one and two equals two—when both are true, the entire statement is true.

Advertisement
Advertisement

To simplify understanding, this truth table captures all outcomes using the specified logical operators:

Take the first row: when "A" istrueand "B" istrue, the expressionA && Bis true.A && Bhere is like writingtrue && true.

In summary, for such expressions to be true:

  • &&: Both must be true

  • ||: At least one must be true

All other conditions are false.

A third operator, "!", flips a condition. It turns true into false, and vice versa:

To make it work in an expected way, place the "!" outside the brackets.

Bash first evaluates everything inside the brackets, then negates the result.

Single vs double bracket notation

The double-bracket notation is modern and more powerful

There are two ways to write Bash if-statements (single and double brackets):s

  • Double brackets: The newer, more robust way that works in a few shells, including Bash

  • Single brackets: The older, less robust way that works in different shells because it's POSIX-compliant

Advertisement
Advertisement

I'd recommend the double-bracket notation, because most Linux systems include a Bash shell. In all my years using Linux, I've never had a single problem running a Bash script. Perhaps if you use Alpine Docker containers (which ship with ash), but that's it. If you add a#!/bin/bashshebang at the top of your script, it will only execute in Bash.

There are some minor differences in how they handle logical operators:

The double-bracket notation also enables features like regex comparisons (=~), and it doesn't split words. These are advanced topics, so skip them if uncomfortable.

Capturing multiple branches

Use if-else and if-elif-else to answer all possible questions

You will almost certainly need to handle multiple branches. To do that, use an if-else statement:

To add more branches, add as many "elif" lines as you need:

Capturing program status

Use commands without brackets to direct program flow

One great reason to use Bash for scripting is how cleanly it handles exit statuses. When a program fails, it returns a non-zero exit code; when it succeeds, it returns zero. We can act on that directly by leaving out the brackets:


We've covered significant ground on Bash if-statements, and what you've learned here will take you far. As already stated, they're a huge chunk of how scripts work, so the time invested is worth the effort.

Advertisement
Advertisement

I'll direct you to the official Bash manual for in-depth learning. It's heavy reading, so I don't recommend you read it from cover to cover, but use it as a reference for the finer details instead.

Advertisement
Advertisement
Mobilize your Website
View Site in Mobile | Classic
Share by: