LinuxCommandLibrary

if

shell conditional statement

TLDR

Basic if statement

$ if [[ condition ]]; then command; fi
copy
If-else
$ if [[ -f file ]]; then echo "exists"; else echo "missing"; fi
copy
If-elif-else
$ if [[ $x -eq 1 ]]; then cmd1; elif [[ $x -eq 2 ]]; then cmd2; else cmd3; fi
copy
Test file exists
$ if [[ -e file ]]; then echo "found"; fi
copy
Test string equality
$ if [[ "$a" == "$b" ]]; then echo "equal"; fi
copy

SYNOPSIS

if condition; then commands; [elif condition; then commands;] [else commands;] fi

DESCRIPTION

if is a shell conditional statement. It executes commands based on the exit status of test conditions.
The construct supports multiple conditions with elif and a fallback else clause. It's fundamental to shell scripting.

PARAMETERS

CONDITION

Test expression.
then
Commands if true.
elif
Else-if clause.
else
Commands if false.
fi
End if block.

CAVEATS

Shell builtin. Spaces in conditions matter. Use [[ ]] in bash.

HISTORY

if is a standard Unix shell construct, present in all POSIX-compliant shells.

SEE ALSO

test(1), case(1), bash(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard

> TERMINAL_GEAR

Curated for the Linux community