Languages
[Edit]
EN

Bash - if...else statement

0 points
Created by:
Root-ssh
179810

In this article, we would like to show you if...else statement in Bash.

Quick solution:

if test_expression
then
    command_1
else
    command_2
fi

Where:

  • test_expression - is the condition that we want to check,
  • then - executes command_1 if the condition is true, 
  • else - executes command_2 if the condition is false,
  • fi - closes the if...else statement.

 

Practical example

In this example, we use echo command that displays a line of text that is passed in as an argument. Using if...else statement we check if directory under given path exists and we display the corresponding message.

#!/bin/bash

if [ -d "path/to/directory" ]
then
	echo "The directory exists."
else 
	echo "The directory does not exist."
fi

 

Alternative titles

  1. Bash - if else statement
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join