Conditionally execute code (if,Β test,Β [ ], etc.)

3. Create Simple Shell Scripts

πŸ“˜Red Hat Certified System Administrator (RHCSA – EX200)


This section is very important for the RHCSA exam. You must know how to make decisions inside a shell script.

Conditional execution allows a script to run certain commands only if a condition is true.

In simple words:

“If something is true, do this. Otherwise, do something else.”

In IT environments, this is used to:

  • Check if a user exists before creating one
  • Verify if a file exists before modifying it
  • Check if a service is running
  • Validate input before continuing
  • Confirm success or failure of commands

1. Understanding Exit Status (Very Important for RHCSA)

Before learning if, you must understand exit codes.

In Linux:

  • Every command returns an exit status
  • 0 β†’ Success (TRUE)
  • Non-zero (1–255) β†’ Failure (FALSE)

Example:

ls /etc
echo $?

If the directory exists, $? will show 0.

If it does not exist:

ls /wrongdir
echo $?

You will see a non-zero value.

πŸ’‘ For shell scripting:

  • 0 = TRUE
  • Non-zero = FALSE

This is opposite of many programming languages.


2. Basic if Statement

Syntax

if CONDITION
then
commands
fi

Example:

if ls /etc > /dev/null 2>&1
then
echo "Directory exists"
fi

Explanation:

  • If the command succeeds β†’ execute the echo
  • If it fails β†’ do nothing

3. Using if with test Command

The test command checks conditions.

Syntax:

test CONDITION

Or more commonly:

[ CONDITION ]

Important:

  • There MUST be a space after [ and before ]
  • [ is actually a command

4. File Condition Tests (Very Important for Exam)

These are commonly tested in RHCSA.

Check if file exists

[ -e filename ]

Check if regular file

[ -f filename ]

Check if directory

[ -d directory ]

Check if file is readable

[ -r filename ]

Check if file is writable

[ -w filename ]

Check if file is executable

[ -x filename ]

Example: Check Before Creating a Backup

#!/bin/bashif [ -f /etc/passwd ]
then
cp /etc/passwd /backup/passwd.bak
echo "Backup created"
fi

In an IT environment:

  • Always verify a file exists before copying or modifying it.

5. String Comparisons

Used when checking usernames, input values, service names, etc.

Equal

[ "$var" = "value" ]

Not equal

[ "$var" != "value" ]

Example:

read usernameif [ "$username" = "admin" ]
then
echo "Administrative user"
fi

⚠ Always use double quotes around variables:

"$var"

This prevents errors if variable is empty.


6. Numeric Comparisons

Used when checking numbers like disk space, process count, user input, etc.

Operators:

MeaningOperator
Equal-eq
Not equal-ne
Greater than-gt
Less than-lt
Greater or equal-ge
Less or equal-le

Example:

read numberif [ "$number" -gt 10 ]
then
echo "Number is greater than 10"
fi

7. if-else Statement

Used when you want two possible outcomes.

Syntax

if CONDITION
then
commands
else
commands
fi

Example:

if [ -d /backup ]
then
echo "Backup directory exists"
else
mkdir /backup
echo "Backup directory created"
fi

This is very common in server setup scripts.


8. if-elif-else Statement

Used when multiple conditions exist.

Syntax

if CONDITION1
then
commands
elif CONDITION2
then
commands
else
commands
fi

Example:

read usertypeif [ "$usertype" = "admin" ]
then
echo "Full privileges"
elif [ "$usertype" = "support" ]
then
echo "Limited privileges"
else
echo "Regular user"
fi

9. Logical Operators

You can combine conditions.

AND (both must be true)

[ condition1 ] && [ condition2 ]

OR inside single test:

[ condition1 -a condition2 ]

Better practice for RHCSA:

if [ -f file ] && [ -r file ]
then
echo "File exists and is readable"
fi

OR (one must be true)

[ condition1 ] || [ condition2 ]

Example:

if [ "$user" = "admin" ] || [ "$user" = "root" ]
then
echo "Privileged user"
fi

10. Using Double Brackets [[ ]]

Modern bash supports:

[[ condition ]]

Advantages:

  • Safer string comparison
  • No need to escape some characters
  • Better pattern matching

Example:

if [[ "$file" == *.conf ]]
then
echo "Configuration file"
fi

For RHCSA, basic [ ] is usually enough, but knowing [[ ]] is helpful.


11. Checking Command Success Directly

You can test a command directly in if.

Example:

if systemctl is-active sshd > /dev/null 2>&1
then
echo "Service is running"
else
echo "Service is not running"
fi

This is extremely common in IT automation scripts.


12. Negation (NOT)

Use ! to reverse a condition.

Example:

if [ ! -f /etc/myconfig.conf ]
then
echo "Configuration file missing"
fi

Meaning:

  • If file does NOT exist

13. Important Exam Tips

For RHCSA, you must:

βœ” Know correct syntax of if, elif, else, fi
βœ” Remember spaces inside [ ]
βœ” Use correct numeric operators (-eq, -gt, etc.)
βœ” Know file test options (-f, -d, -r, -w, -x)
βœ” Understand exit status (0 = success)
βœ” Quote variables properly: "$var"
βœ” Be able to write small working scripts


14. Common Mistakes (Avoid in Exam)

❌ Missing space:

if["$a"="b"]

Correct:

if [ "$a" = "b" ]

❌ Using = for numeric comparison:

[ "$num" = 5 ]

Correct:

[ "$num" -eq 5 ]

❌ Forgetting fi at the end

❌ Not making script executable:

chmod +x script.sh

15. Complete RHCSA-Level Example Script

#!/bin/bashread -p "Enter username: " userif id "$user" > /dev/null 2>&1
then
echo "User exists"
else
useradd "$user"
echo "User created"
fi

What this script does:

  • Checks if user exists
  • If yes β†’ prints message
  • If not β†’ creates user

This type of logic is commonly expected in the exam.


Final Summary

For RHCSA EX200, conditional execution means:

  • Using if, elif, else, fi
  • Using [ ] or test
  • Understanding exit codes
  • Performing file, string, and numeric comparisons
  • Combining conditions using AND/OR
  • Checking command success
  • Using negation

If you can:

  • Write a script that checks file existence
  • Compare numbers correctly
  • Verify user/service status
  • Handle multiple conditions

Then you are fully prepared for this section of the RHCSA exam.

Buy Me a Coffee