Windows
Linux
Terminal & Shell Scripting
Terminal
Windows if equivalent in Linux
Tests a condition and executes different code depending on whether it is true or false.
Windows
→
if
Linux equivalents
if [ condition ]; then ... fi
if [ condition ]; then ... fi
if [ condition ]; then ... fi
Overview
What this command does
Tests a condition and executes different code depending on whether it is true or false.
Migration tip: Use
[[ ]] (double brackets) in bash — it's more powerful than [ ] and handles edge cases better. Always quote variables: "$var" not $var.Practical tasks
Common use cases
Conditional branching in scripts
Tests a condition and executes different code depending on whether it is true or false.
[ -f file ]
True if file exists
[ -d dir ]
True if directory exists
[ -z "$var" ]
True if variable is empty
Ready to run
Copyable Linux commands
Review paths, device names, package names and permissions before running any command.
if [ -f "/etc/hosts" ]; then
echo "File exists"
fi
if [ "$USER" = "root" ]; then
echo "Running as root"
else
echo "Normal user"
Walkthrough
Examples with explanations
# Windows: if exist file.txt echo yes
if [ -f "/etc/hosts" ]; then
echo "File exists"
fi
# if/else:
if [ "$USER" = "root" ]; then
echo "Running as root"
else
echo "Normal user"
fi
Reference
Common options and variations
| Command or option | Use |
|---|---|
[ -f file ] | True if file exists |
[ -d dir ] | True if directory exists |
[ -z "$var" ] | True if variable is empty |
[ "$a" = "$b" ] | String equality |
[ $a -eq $b ] | Numeric equality |
[ $a -gt $b ] | Numeric greater-than |
Distro differences
Debian/Ubuntu vs Fedora vs Arch
This command is the same on Debian/Ubuntu, Fedora and Arch Linux when the relevant tool is installed.
| Distribution | Package manager / base | Equivalent command | Difference to notice |
|---|---|---|---|
| Debian/Ubuntu | same command | if [ condition ]; then ... fi |
Same command on this distribution. |
| Fedora | same command | if [ condition ]; then ... fi |
Same command on this distribution. |
| Arch | same command | if [ condition ]; then ... fi |
Same command on this distribution. |
Important
What to watch out for
Spaces inside brackets are mandatory: [ $x -eq 1 ] works but [$x -eq 1] does not.
Keep learning