Operations 5 min read

Shell Conditional Statements and Test Operators: Syntax, Examples, and Usage

This article explains the various shell test operators for file types, permissions, comparisons, and strings, demonstrates single‑branch if statements, and provides practical Bash scripts for checking the current user and monitoring root partition usage.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
Shell Conditional Statements and Test Operators: Syntax, Examples, and Usage

1. Condition test statements – The article introduces file‑type tests such as -d (directory), -e (exists), -f (regular file) and shows two syntaxes: test -e /root/install.log and [ -e /root/install.log ]. It also covers permission tests ( -r, -w, -x), file‑time comparisons ( -nt, -ot), inode comparison ( -ef), integer comparisons ( -eq, -ne, -gt, -lt, -ge, -le) and string tests ( -z, -n, ==, !=).

2. Single‑branch if statement – Shell’s if syntax differs from most languages; it uses if [ condition ]; then … fi or a newline after then. Logical operators -a (and), -o (or) and negation ! are described.

3. Example: checking whether the current user is root

#!/bin/bash
# script: this is user root
# write: yzc
# date: 20190226
test=$(env | grep "USER" | cut -d "=" -f2)
if [ "$test" == "root" ]; then
    echo -e "dangqianyonghushi root"
fi

This script extracts the USER environment variable, compares it to "root", and prints a message if the comparison succeeds.

4. Example: checking root partition usage

#!/bin/bash
# script: 判断根分区使用率
# write: hahashen
# date: 20190226
test=$(df -h | grep "/dev/mapper/centos-root" | awk '{print $5}' | cut -d "%" -f1)
if [ "$test" -ge "36" ]; then
    echo "/ is full"
fi

The script obtains the usage percentage of the root filesystem, and if it is 36% or higher, it outputs a warning. The article also shows how to make the script executable ( chmod 755 if2.sh) and run it.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

conditional statementsFile Permissionstest operators
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.