How to use conditional statements (if-else) in a Bash script?

To use conditional statements (if-else) in a Bash script, you can follow these steps:

  1. Start by opening a text editor and creating a new Bash script file with a .sh extension. For example, you can use the command nano script.sh to create and open a new file named script.sh in the nano text editor.

  2. Begin the script by adding a shebang at the top, which specifies the interpreter to be used. In this case, #!/bin/bash denotes that the script should be interpreted using the Bash shell.

  3. Define the code block inside the if statement. For example, you can check if a particular condition is true or false. The syntax for an if statement in Bash is as follows:

if [ condition ]; then # code block executes when the condition is true fi
  1. Optionally, you can add an else block to execute code when the condition is false:
if [ condition ]; then # code block executes when the condition is true else # code block executes when the condition is false fi
  1. Replace [ condition ] with the actual condition that you want to check. You can use various comparison operators in Bash, such as -eq, -ne, -lt, -gt, -le, and -ge for numeric comparisons, or ==, !=, <, >, <=, and >= for string comparisons. For example:
if [ $number -eq 10 ]; then echo "The number is equal to 10." fi if [ $name == "John" ]; then echo "Hello John!" else echo "Hello someone else!" fi
  1. Save and exit the text editor.

  2. Make the script executable by running the command chmod +x script.sh.

  3. Execute the script in the terminal using the command ./script.sh. The output will depend on the condition you provided.

These steps outline the basic usage of conditional statements (if-else) in a Bash script. You can expand on this concept by using nested if-else statements, logical operators (&& for "and" and || for "or"), and more complex conditions.