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

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 “”:
  1. Type the following code into the file:

# Declaring a variable

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

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

And that’s it! Remember:


Leave a Reply

Scroll to Top