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 test command, various bracket operators, and the if/then construct 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
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 builtinUsing if/then with Any Command
#!/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.'
fiBasic if/then Syntax
if [ condition-true ]
then
command1
command2
...
else
# optional elif ...
command3
command4
...
fiExtended if/then with elif
if [ condition1 ]
then
command1
command2
command3
elif [ condition2 ]
then
command4
command5
else
default-command
fiArithmetic Tests with (( ))
#!/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 0Numeric 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
#!/bin/bash
num1=6
num2=9
if [ $num1 -ne $num2 ]
then
echo "$num1 is not equal to $num2"
fiString 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
#!/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."
fiSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
