Bash script if else

  • Read
  • Discuss

The if statement in bash script is used to conditionally execute a command based on the exit status of a test command. The basic syntax of an if statement is:

if [ test_command ]; then
  commands
fi

How Do I Use Conditional Statements in a Bash Script?

  1. Open your terminal or shell.
  2. Create a new file using a text editor of your choice. For example, you can use the nano editor to create a file called “ifelse.sh”:
nano ifelse.sh
  1. Type the following code into the file:
#!/bin/bash

# Declaring a variable
age=30

# Using the if statement to check the value of a variable
if [ $age -gt 18 ]; then
  echo "You are an adult."
else
  echo "You are a minor."
fi
  1. Save the file and exit the editor.
  2. Make the file executable by running the following command in the terminal:
chmod +x ifelse.sh
  1. Finally, run the script by typing:
./ifelse.sh

You should see the message “You are an adult.” printed in the terminal.

And that’s it! Remember:

Bash-Tips-if-statement

Leave a Reply

Scroll to Top