|
Home | Switchboard | Unix Administration | Red Hat | TCP/IP Networks | Neoliberalism | Toxic Managers |
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix |
The internal test command is used to evaluate conditional expressions. The test command evaluates the expression and, if it is true, returns a 0 return code; if the expression is false, the return code is 1. The test command is primarily used to make a conditional decision in a shell script. The following features are provided:
There are internal versions of test in the csh and ksh and an external version in /bin/test.
Following is the general format of the test command.
test expr [ expr ]
The brackets ([]) are an alternative to the test syntax. You must place blanks before and after the first bracket and before the second one. Thus the following two syntaxes are equivalent:
if test -f file if [ -f file ]
The test command has primary expressions (operators) that perform one specific conditional check. These primary expressions can be combined using operators. The following three sections cover the primary expressions used to test files, strings, and numbers.
Testing on files
These primitives can be used to test the state, type, or permissions of a file. The file may be a constant or variable.
NOTE:
If a file does not exist or the condition is false, test returns an exist status of nonzero. If the condition is true, test returns an exit status of 0.
|
|
Expression | Description |
---|---|
|
|
-b file | True if file exists and is a block special file. |
-c file | True if file exists and is a character special file. |
-d file | True if file exists and is a directory. |
-f file | True if file exists and is a regular file. |
-g file | True if file exists and has the set-group-ID bit set. |
-k file | True if file exists and has the sticky bit set. |
-p file | True if file exists and is a pipe. |
-r file@LIST2= | True if file exists and is readable. |
-s file | True if file exists and has a size greater than 0 bytes. |
-t [fds] | True if the open file defined by file descriptor "fds" is a tty(default fds=1). |
-u file | True if file exists and has the set-user-ID bit set. |
-w file | True if file exists and is writable. |
-x file | True if file exists and is executable. |
|
|
Korn Shell Extensions | |
-L file | True if file exists and is a symbolic link. |
file1 -nt file2 | True if file1 is newer than file2. |
file1 -ot file2 | True if file1 is older than file2. |
file1 -ef file2 | True if file1 has the same device and inode number as file2. |
|
|
If file is of the form /dev/fd/n, where n is an integer, the test is applied to the open file whose descriptor number is n. | |
|
|
BSD (Berkeley) | |
Only the following file testing options exist in BSD versions. | |
-L file | True if file exists and is a soft link. |
-d file | True if file exists and is a directory. |
-f file | True if file exists and is a regular file. |
-r file | True if file exists and is readable. |
-s file | True if file exists and has a size greater than 0 bytes. |
-t [fds] | True if the open file defined by file descriptor "fds" is a tty(default fds=1). |
-w file | True if file exists and is writable. |
|
NOTE:
It is advisable to enclose string variables within double quotes. This ensures that test will work even if the variable is unset or null.
Testing on strings
The following primitives can be used to test the condition of strings. The sX values may be a constant or a variable. The double quotes around the sX values are not necessary but are advisable.
|
|
Expression | Description |
---|---|
|
|
-z "s1" | True if length of string s1 is zero. |
"s1" = "s2" | True if strings s1 and s2 are equal(match). |
"s1" != "s2" | True if strings s1 and s2 are NOT equal. |
"s1" | True if s1 exists; is not a null string. |
The = and != operators have higher precedence than the -b through -z operators. | |
|
|
BSD (Berkeley) | |
BSD supports all of these options. | |
|
Testing on numbers
The following primitives can be used to test the condition of two numbers. The double quotes around the sX values are not necessary but are advisable.
|
|
Expression | Description |
---|---|
|
|
n1 -eq n2 | True if n1 and n2 are equal. |
n1 -ne n2 | True if n1 and n2 are NOT equal. |
n1 -gt n2 | True if n1 is greater than n2. |
n1 -ge n2 | True if n1 is greater than or equal to n2. |
n1 -lt n2 | True if n1 is less than n2. |
n1 -le n2 | True if n1 is less than or equal to n2. |
|
|
BSD (Berkeley) | |
BSD supports all of these options. | |
|
OPERATORS
The following operators may be placed between expressions, except for the parentheses, which are placed around expressions for grouping.
|
||
Expression | Description | |
---|---|---|
|
||
! expr | Unary negation operator. Unary means it only
negates one expression, the one immediately following it. To negate
multiple expressions enclose them in parentheses. For example, |
|
[ ! -w myfile ] | ||
returns true if myfile does not exists or
is not writable. While |
||
[ ! \( -r myfile -a -w myfile \) ] | ||
returns true if myfile does not exist or is not readable and writable. | ||
expr -a expr@T2=Binary and
operator. Binary means it operates on two expressions, the one before
and the one after the -a. The result is true if both expressions
are true. If one or both expressions are false, then the result
of the test is false. For example, |
||
[ -r myfile -a -s myfile ] | ||
returns true if you can read myfile and it is not empty. | ||
expr -o expr | Binary or operator. The result is true if
one or both of the expressions are true. If both expressions are
false, then the result of the test is false. For instance, |
|
[ "$ANS" = "Y" -o "$ANS" = "X" ] | ||
returns true if the value of $ANS equals Y or X. | ||
( expr ) | Expression grouping parentheses. You may need to group expressions when using operators to force the correct interpretation of the operators. The test command evaluates with the following precedence, from high to low: | |
(!), !, -a, -o | ||
For example, |
||
[ ! -r myfile -a -x myfile ] | ||
returns true if myfile is not readable and
is executable. Whereas, |
||
[ ! \( -r myfile -a -x myfile \) ] | ||
returns true if myfile is not readable, not writable, or both. |
|
BSD (Berkeley) |
---|
BSD supports all of these operators. |
|
FURTHER DISCUSSION
The test command is normally used in shell scripts to test expressions and return an exit status to the if, until, and while constructs.
When using variables in the test command you should always surround the variable with double quotes unless they are being compared as numbers. For instance, if you had the variable FILE, you would type
if [ "${FILE}" = "myfile" ]
This syntax will prevent the test command from aborting if the variable is not set or has a NULL value.
DIAGNOSTICS AND BUGS
If you own a file and test for a condition of -r, -w, or -x, you may not receive the correct results. If the file permissions are not set in the owner field for the condition being tested, the result of the test will be false. In short, the test command looks at the permissions that relate to you using the file.
RELATED COMMANDS
Refer to the ksh command described in Module 71.
RETURN CODES
The test command returns a 0 if the expressions evaluated were true. If the expressions where false then a 1 is returned.
APPLICATIONS
You can use test in shell scripts to test for file permissions and to compare the values of variables. Normally, you use test in conjunction with the programming constructs of the shell. For example,
cj> while [ -n "$*" ] do echo $1 shift done
would test for the existence of parameters. When no more parameters existed the loop would exit because test returns a false (return code 1) value.
TYPICAL OPERATION
In this activity you use the test command to make sure a file is readable before you try to read it. Begin at the shell prompt.
cj> cat > mycat if [ -r "$1" ] then cat $1 else echo "You Do Not Have Read Permission for $1" fi ^D
|
||
---|---|---|
C Shell | ||
cj> cat > mycat #1/bin/csh test -r $1 if ( $status == 0 ) then |
||
cat $1 | ||
else | ||
echo "You Do Not Have Read Permission for $1" | ||
endif ^D |
||
|
Society
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
Quotes
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Bulletin:
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
History:
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
Classic books:
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D
Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
|
You can use PayPal to to buy a cup of coffee for authors of this site |
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.
Last modified: March 12, 2019