Master Bash Test Commands: Conditional Expressions, Comparisons, and File Checks
This article explains Bash's test command and related conditional operators, demonstrates various if/then syntaxes, arithmetic and string comparisons, and shows how to test file attributes with practical code examples for Linux shell scripting.
Shell Test Command Overview
Every programming language can evaluate a condition and act based on the result; Bash provides the
testcommand, various bracket operators, and the
if/thenconstruct for this purpose.
Related Commands and Symbols
If/then conditional statements.
Built‑in
[]and enhanced
[[]]brackets.
Arithmetic evaluation with
(( ))and
let.
Checking Built‑in Types
<code>type test # test is a shell builtin</code>
<code>type [ # [ is a shell builtin</code>
<code>type [[ # [[ is a shell keyword</code>
<code>type let # let is a shell builtin</code>Using if/then with Any Command
<code>#!/bin/bash
if cmp a.txt b.txt > /dev/null
then
echo 'Files a and b are identical.'
else
echo 'Files a and b are diff.'
fi</code>Basic if/then Syntax
<code>if [ condition-true ]
then
command1
command2
...
else
# optional elif ...
command3
command4
...
fi</code>Extended if/then with elif
<code>if [ condition1 ]
then
command1
command2
command3
elif [ condition2 ]
then
command4
command5
else
default-command
fi</code>Arithmetic Tests with (( ))
<code>#!/bin/bash
var1=7
var2=10
if (( var1 > var2 ))
then
echo "var1 is greater than var2"
else
echo "var1 is less than var2"
fi
exit 0</code>Numeric Comparison Operators
Common test operators for numbers include:
-eq: equal
-ne: not equal
-gt: greater than
-ge: greater than or equal
-lt: less than
-le: less than or equal
<code>#!/bin/bash
num1=6
num2=9
if [ $num1 -ne $num2 ]
then
echo "$num1 is not equal to $num2"
fi</code>String Comparison Operators
str1 = str2: strings are identical
str1 != str2: strings differ
-z str1: string is empty
-n str1: string is non‑empty
str1 > str2: string1 sorts after string2
str1 < str2: string1 sorts before string2
File Attribute Tests
-e file: file exists
-r file: file is readable
-w file: file is writable
-x file: file is executable
-s file: file is non‑empty
-d file: file is a directory
-f file: file is a regular file
-c file: file is a character device
-b file: file is a block device
<code>#!/bin/bash
device1="/dev/sda1"
if [ -b "$device1" ]
then
echo "$device1 is a block device."
fi
device2='/dev/tty0'
if [ -c "$device2" ]
then
echo "$device2 is a character device."
fi</code>Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.