Lesson 17 of 17

Conditionals

Making Decisions

Shell scripts can take different actions based on conditions. The if statement is the primary tool for this.

Basic if / else

if [ condition ]; then
  echo "condition is true"
else
  echo "condition is false"
fi

The [ command evaluates the condition and returns true or false. fi ends the block (it is if spelled backward).

File Tests

The most common conditions check whether files exist:

TestTrue when
-f FILEFILE exists and is a regular file
-d FILEFILE exists and is a directory
-e FILEFILE exists (file or directory)

Example:

if [ -f hello.txt ]; then
  echo "File exists"
else
  echo "Not found"
fi

Since hello.txt exists, the output is:

File exists

String Tests

TestTrue when
"$A" = "$B"strings are equal
"$A" != "$B"strings differ
-z "$A"string is empty
-n "$A"string is non-empty

Number Tests

TestTrue when
$A -eq $Bequal
$A -ne $Bnot equal
$A -lt $Bless than
$A -gt $Bgreater than

Your Task

Write an if statement that checks whether hello.txt exists. If it does, print File exists. Otherwise, print Not found.

Linux shell loading...
Loading...
Click "Run" to execute your code.