Windows if equivalent in Linux
Tests a condition and executes different code depending on whether it is true or false.
if
if [ condition ]; then ... fi
if [ condition ]; then ... fi
if [ condition ]; then ... fi
Overview
What this command does
On Windows, "if" is used to conditional branching in scripts. On Linux, the closest practical mapping shown here is "if [ condition ]; then ... fi". Tests a condition and executes different code depending on whether it is true or false. This reference is grouped under Terminal & Shell Scripting → Terminal.
Windows → Linux context
What changes when you use this on Linux?
Same name, different environment
The basic command name if is familiar on both platforms, but Linux path rules, quoting, permissions and available options can still change the result.
Portable across the compared distros
The Debian/Ubuntu, Fedora and Arch rows use the same command in this mapping. Package availability or defaults can still vary, so check the installed tool version when an option behaves differently.
Command-specific caution
Spaces inside brackets are mandatory: [ $x -eq 1 ] works but [$x -eq 1] does not.
For the broader concept behind this mapping, read Linux command-line basics.
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
Debian/Ubuntu, Fedora and Arch all use "if [ condition ]; then ... fi" for this mapping. The command syntax shown here is portable across the three rows, although installed versions and system defaults can still vary.
| 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
Keep learning