MJUN Tech Note

Conditional Branching with test Command in Shell Script

This article covers the test command used for conditional branching in shell scripts. It enumerates what types of conditional branching are possible based on the options of the test command. Since it’s intended for use in shell scripts, the notation uses [ ].

ConditionDescription
-a fileTrue if file exists
-d fileTrue if file is a directory
-e fileTrue if file exists
-f fileTrue if file is a regular file
-h fileTrue if file is a symbolic link
-r fileTrue if file is readable
-s fileTrue if file size is greater than 0
-w fileTrue if file is writable
-x fileTrue if file is executable
a -nt bTrue if a is newer than b in modification time
a -ot bTrue if a is older than b in modification time
-z strTrue if str is an empty string
-n strTrue if str is not an empty string
str1 = str2True if str1 and str2 are the same
str1 == str2True if str1 and str2 are the same
str1 != str2True if str1 and str2 are different
str1 < str2True if str1 comes before str2 in dictionary order
str1 > str2True if str1 comes after str2 in dictionary order
a -eq bTrue if numbers a and b are equal
a -ne bTrue if numbers a and b are not equal
a -lt bTrue if a is less than or equal to b
a -le bTrue if a is less than b
a -gt bTrue if a is greater than b
a -ge bTrue if a is greater than or equal to b

References

Books

[改訂第3版]シェルスクリプト基本リファレンス ──#!/bin/shで、ここまでできる (WEB+DB PRESS plus)