Conditional Operators in Linux

Below is a list of conditional operators for Unix shell scripting

For Numbers

num1 -eq num2 True if num1 equals num2.

num1 -ne num2 True if num1 is not equal to num2.

num1 -lt num2 True if num1 is less than num2.

num1 -gt num2 True if num1 is greater than num2.

num1 -le num2 True if num1 is less than or equal to num2.

num1 -ge num2 True if num1 is greater than or equal to num2.

Characters

str1 = str2 True if str1 and str2 are identical.

str1 != str2 True if str1 and str2 are not identical.

-n str1 True if str1 is not null (length is greater than zero).

-z str1 True if str1 is null (length is zero).

For Files

-f somefile True if somefile exists and is an ordinary file.

-d somefile True if somefile exists and is a directory.

-s somefile True if somefile contains data (the size is not zero).

-r somefile True if somefile is readable.

-w somefile True if somefile is writable.

-x somefile True if somefile is executable.

Logical Operators

cond1 -a cond2 True if both cond1 and cond2 are true.

cond1 -o cond2 True if either cond1 or cond2 is true.

! cond1 True if cond1 is false.

Date Formats

Below are a number of unix date formats that can be feed into the command date '+format'

Time Formatting

%H - Hour in 24 hour format (00-23)
%M - Minutes (00-59)
%S - Second (00-61) 61 permits leap seconds.
%I - Hour in 12 hour format. (01-12)
%p - PM or AM

Full Time Formatting

%R - Time in %H:%M
%T - Time in %H:%M:%S
%r - Time in %I:%M:%S %p

Day Formatting

%d - Day of month (01-31)
%e - Day of month (1-31) with single digits padded with space.
%a - Abbreviated weekday
%A - Full weekday
%w - Day of week (Sunday=0)

Month Formatting

%m - Month of year (01-12)
%b - abbreviated month name
%h - Same as %b
%B - Full month name

Year Formatting

%y - Last two digits of year (00-99)
%Y - Four digit year. e.g. 2010

Full Date Formatting

%D - Date in %m/%d/%y

Miscellaneous

%U - Week number in year (00-53). Start week on Sunday.
%W - Week number in year (00-53) - Start week on Monday.
%j - Julian day of year (001-366).
%Z - Time zone name
%x - Country specific date format.
%X - Country specific time format.
%c - Country specfic date and time format. (%a %b %e %T %Z %Y; e.g. Mon 1 Jan 00:01:59 GMT)
%n - Insert newline
%t - Insert a tab

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License