TEST(1POSIX)

๐ŸŽ€ TEST(1POSIX) ๐ŸŽ€

okay bestie, welcome to the POSIX Programmer's Manual โ€” this is TEST(1POSIX), the vibe-check utility, and she is iconic. ๐Ÿ’…


๐ŸŒธ PROLOG ๐ŸŒธ

real talk before we start: this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ โ€” so like, consult the corresponding Linux manual page for details of Linux behavior, okay? Or the interface may not be implemented on Linux at all. ๐Ÿ™ˆ no cap, always check.


โœจ NAME โœจ

test โ€” evaluate expression ๐Ÿ’–


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

test [expression]

[ [expression] ]

๐Ÿ‘‘ DESCRIPTION ๐Ÿ‘‘

So the test utility shall evaluate the expression and tell you the tea by its exit status. And the tea is:

  • an exit status of zero means the expression evaluated as true โœ…
  • an exit status of 1 means the expression evaluated as false โŒ

periodt. that's the whole personality.

Now, in the second form of the utility โ€” where the utility name used is [ instead of test โ€” the application shall ensure that the closing square bracket is a separate argument. yes bestie, you literally have to pass the ] as its own lil argument. don't try to sneak it in attached to something, she will NOT be fooled. ๐Ÿ˜ญ

Also, plot twist: the test and [ utilities may be implemented as a single linked utility which examines the basename of the zeroth command line argument to figure out whether to behave as the test variant or the [ variant. main character energy, one binary two personalities fr fr. ๐Ÿซถ

And here's the part where you gotta be careful โ€” applications using the exec() family of functions to execute these utilities shall ensure that:

  • the argument passed in arg0 or argv[0] is '[' when executing the [ utility
  • that same argument has a basename of "test" when executing the test utility

so like, get your argv[0] right or she genuinely will not know who she is. ๐Ÿ’€


๐Ÿ’… OPTIONS ๐Ÿ’…

okay so here's the thing, and it's giving minimalist:

The test utility shall not recognize the "--" argument in the manner specified by Guideline 10 in the Base Definitions volume of POSIX.1โ€2017, Section 12.2, Utility Syntax Guidelines.

like, she's not doing the -- thing. that's just not her era. ๐Ÿšซ

And โ€” drumroll โ€” no options shall be supported. ๐ŸŽ€

none. zero. not a single one. she said no options, and she meant it. โœจ


๐Ÿฆ‹ OPERANDS ๐Ÿฆ‹

Okay bestie, listen up โ€” this is where it gets real. ๐Ÿ’… Your app has to make sure that all operators and elements of primaries are presented as separate arguments to the test utility. No squishing things together, fr fr.

Here's the lineup of primaries you can use to build an expression, and I'm giving you every single one because we don't do gatekeeping here. ๐Ÿซถ

  • -b pathname โ€” True if pathname resolves to an existing directory entry for a block special file. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a block special file.
  • -c pathname โ€” True if pathname resolves to an existing directory entry for a character special file. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a character special file.
  • -d pathname โ€” True if pathname resolves to an existing directory entry for a directory. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a directory.
  • -e pathname โ€” True if pathname resolves to an existing directory entry. False if pathname can't be resolved. That's it, that's the whole vibe. โœจ
  • -f pathname โ€” True if pathname resolves to an existing directory entry for a regular file. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a regular file.
  • -g pathname โ€” True if pathname resolves to an existing directory entry for a file that has its set-group-ID flag set. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that does not have its set-group-ID flag set.
  • -h pathname โ€” True if pathname resolves to an existing directory entry for a symbolic link. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a symbolic link. And the tea โ˜•: if the final component of pathname is a symbolic link, that symbolic link is not followed.
  • -L pathname โ€” Same energy as -h, literally. True if pathname resolves to an existing directory entry for a symbolic link. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a symbolic link. And again โ€” if the final component of pathname is a symbolic link, that symbolic link is not followed.
  • -n string โ€” True if the length of string is non-zero; otherwise, false.
  • -p pathname โ€” True if pathname resolves to an existing directory entry for a FIFO. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a FIFO.
  • -r pathname โ€” True if pathname resolves to an existing directory entry for a file for which permission to read from the file will be granted, as defined in Section 1.1.1.4, File Read, Write, and Creation. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file for which permission to read from the file will not be granted.
  • -S pathname โ€” True if pathname resolves to an existing directory entry for a socket. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that is not a socket.
  • -s pathname โ€” True if pathname resolves to an existing directory entry for a file that has a size greater than zero. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that does not have a size greater than zero.
  • -t file_descriptor โ€” True if file descriptor number file_descriptor is open and is associated with a terminal. False if file_descriptor is not a valid file descriptor number, or if file descriptor number file_descriptor is not open, or if it is open but is not associated with a terminal.
  • -u pathname โ€” True if pathname resolves to an existing directory entry for a file that has its set-user-ID flag set. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file that does not have its set-user-ID flag set.
  • -w pathname โ€” True if pathname resolves to an existing directory entry for a file for which permission to write to the file will be granted, as defined in Section 1.1.1.4, File Read, Write, and Creation. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file for which permission to write to the file will not be granted.
  • -x pathname โ€” True if pathname resolves to an existing directory entry for a file for which permission to execute the file (or search it, if it is a directory) will be granted, as defined in Section 1.1.1.4, File Read, Write, and Creation. False if pathname can't be resolved, or if it resolves to an existing directory entry for a file for which permission to execute (or search) the file will not be granted.
  • -z string โ€” True if the length of string string is zero; otherwise, false.
  • string โ€” True if the string string is not the null string; otherwise, false.
  • s1 = s2 โ€” True if the strings s1 and s2 are identical; otherwise, false.
  • s1 != s2 โ€” True if the strings s1 and s2 are not identical; otherwise, false.
  • n1 -eq n2 โ€” True if the integers n1 and n2 are algebraically equal; otherwise, false.
  • n1 -ne n2 โ€” True if the integers n1 and n2 are not algebraically equal; otherwise, false.
  • n1 -gt n2 โ€” True if the integer n1 is algebraically greater than the integer n2; otherwise, false.
  • n1 -ge n2 โ€” True if the integer n1 is algebraically greater than or equal to the integer n2; otherwise, false.
  • n1 -lt n2 โ€” True if the integer n1 is algebraically less than the integer n2; otherwise, false.
  • n1 -le n2 โ€” True if the integer n1 is algebraically less than or equal to the integer n2; otherwise, false.
  • expression1 -a expression2 โ€” True if both expression1 and expression2 are true; otherwise, false. The -a binary primary is left associative. It has a higher precedence than -o. ๐Ÿ‘‘
  • expression1 -o expression2 โ€” True if either expression1 or expression2 is true; otherwise, false. The -o binary primary is left associative.

With the exception of the -h pathname and -L pathname primaries, if a pathname argument is a symbolic link, test shall evaluate the expression by resolving the symbolic link and using the file referenced by the link. So like, -h and -L are the rebels that refuse to follow links. Iconic behaviour honestly. ๐Ÿ™ˆ


These primaries can be combined with the following operators:

  • ! expression โ€” True if expression is false. False if expression is true. The classic plot twist. ๐Ÿ’€
  • ( expression ) โ€” True if expression is true. False if expression is false. The parentheses can be used to alter the normal precedence and associativity.

๐ŸŽ€ Unary and binary primaries ๐ŸŽ€

The primaries with two elements of the form:

-primary_operator primary_operand

are known as unary primaries.

The primaries with three elements in either of the two forms:

primary_operand -primary_operator primary_operand

primary_operand primary_operator primary_operand

are known as binary primaries.

Additional implementation-defined operators and primary_operators may be provided by implementations. They shall be of the form -operator where the first character of operator is not a digit. Noted, bestie. ๐Ÿ“


โœจ The precedence algorithm (aka the vibe check) โœจ

The algorithm for determining the precedence of the operators and the return value that shall be generated is based on the number of arguments presented to test. (However, when using the "[...]" form, the <right-square-bracket> final argument shall not be counted in this algorithm.)

In the following list, $1, $2, $3, and $4 represent the arguments presented to test:

  • 0 arguments: Exit false (1).
  • 1 argument: Exit true (0) if $1 is not null; otherwise, exit false.
  • 2 arguments:
    • If $1 is '!', exit true if $2 is null, false if $2 is not null.
    • If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.
    • Otherwise, produce unspecified results.
  • 3 arguments:
    • If $2 is a binary primary, perform the binary test of $1 and $3.
    • If $1 is '!', negate the two-argument test of $2 and $3.
    • If $1 is '(' and $3 is ')', perform the unary test of $2. On systems that do not support the XSI option, the results are unspecified if $1 is '(' and $3 is ')'.
    • Otherwise, produce unspecified results.
  • 4 arguments:
    • If $1 is '!', negate the three-argument test of $2, $3, and $4.
    • If $1 is '(' and $4 is ')', perform the two-argument test of $2 and $3. On systems that do not support the XSI option, the results are unspecified if $1 is '(' and $4 is ')'.
    • Otherwise, the results are unspecified.
  • >4 arguments: The results are unspecified.

On XSI-conformant systems, combinations of primaries and operators shall be evaluated using the precedence and associativity rules described previously. In addition, the string comparison binary primaries '=' and "!=" shall have a higher precedence than any unary primary. Periodt. ๐Ÿ’…

โš ๏ธ Not me warning you: a lot of these branches say "unspecified results". That's not a cute lil mystery, that's literally undefined behaviour territory. Keep your argument counts clean, bestie. ๐Ÿ˜ญ

๐ŸŒˆ STDIN ๐ŸŒˆ

Not used. She doesn't read from stdin, she's not that kind of girl. ๐Ÿ’œ


๐Ÿ“ INPUT FILES ๐Ÿ“

None. Nada. Zero. The vibes are self-contained. โœจ

๐ŸŒธ ENVIRONMENT VARIABLES ๐ŸŒธ

ok so bestie, these are the env vars that can ~influence~ how test does its thing:

  • LANG โ€” gives you a default value for the internationalization variables that are unset or null. (fr, if you wanna see how the precedence of i18n variables works when figuring out locale categories, go peek at the Base Definitions volume of POSIX.1โ€2017, Section 8.2, Internationalization Variables.) ๐Ÿ’…
  • LC_ALL โ€” if you set this to a non-empty string value, it overrides all the other internationalization variables. like, all of them. it's the main character. ๐Ÿ‘‘
  • LC_CTYPE โ€” decides the locale used for interpreting sequences of bytes of text data as characters (think single-byte vs multi-byte characters in arguments). lowkey important!! โœจ
  • LC_MESSAGES โ€” decides the locale that affects the format and contents of diagnostic messages written to standard error. ๐Ÿซถ
  • NLSPATH โ€” decides where the message catalogs live for the processing of LC_MESSAGES. ๐Ÿ“

โฐ ASYNCHRONOUS EVENTS โฐ

Default. nothing special here, moving on ๐Ÿ’€

๐Ÿ“ค STDOUT ๐Ÿ“ค

Not used. like, at all. it's giving silent. ๐Ÿค

๐Ÿ“ฅ STDERR ๐Ÿ“ฅ

The standard error shall be used only for diagnostic messages. that's its whole job, and it's doing it beautifully ๐Ÿ’…

๐Ÿ“ OUTPUT FILES ๐Ÿ“

None. zero. nada. ๐ŸŽ€

๐Ÿฆ‹ EXTENDED DESCRIPTION ๐Ÿฆ‹

None. nothing to see here bestie, keep scrolling โœจ

๐Ÿšฆ EXIT STATUS ๐Ÿšฆ

okay so these are the exit values you get back, and honestly they're the whole point of the program:

  • 0 โ€” expression evaluated to true. slay!! ๐ŸŽ‰
  • 1 โ€” expression evaluated to false, or the expression was missing. (yeah, missing counts as a 1. rude but true.)
  • >1 โ€” an error occurred. something went wrong bestie ๐Ÿ˜ญ

๐Ÿ’€ CONSEQUENCES OF ERRORS ๐Ÿ’€

Default.

heads up: everything from here down is informative. it's the bonus lore, not the normative rules. iykyk ๐Ÿ“–

๐Ÿ› ๏ธ APPLICATION USAGE ๐Ÿ› ๏ธ

okay this is the part where the manpage gets REAL and starts spilling tea about portability. buckle up ๐Ÿซถ

The XSI extensions that specify the -a and -o binary primaries and the ( and ) operators have been marked obsolescent. (why? because SO many expressions using them are ambiguously defined by the grammar, depending on the specific expressions being evaluated. it's giving chaos.) Scripts using these expressions should be converted to the forms given below. And even though lots of implementations will keep supporting these obsolescent forms, scripts need to be extremely careful when dealing with user-supplied input that could get confused with these and other primaries and operators. like, unless the application developer knows all the cases that produce input to the script, invocations like:

test "$1" -a "$2"

should be written as:

test "$1" && test "$2"

so you avoid problems if a user supplies values such as $1 set to '!' and $2 set to the null string. so basically, in cases where maximal portability is the concern, replace:

test expr1 -a expr2

with:

test expr1 && test expr2

and replace:

test expr1 -o expr2

with:

test expr1 || test expr2

but โ€” and this is the plot twist โ€” note that in test, -a has higher precedence than -o, while "&&" and "||" have equal precedence in the shell. so they are not the same thing, bestie, do not get it twisted ๐Ÿ˜ญ

Parentheses or braces can be used in the shell command language to effect grouping.

Parentheses must be escaped when using sh; for example:

test \( expr1 -a expr2 \) -o expr3

This command is not always portable even on XSI-conformant systems, depending on the expressions specified by expr1, expr2, and expr3. The following form can be used instead:

( test expr1 && test expr2 ) || test expr3

Now the two commands:

test "$1"
test ! "$1"

could not be used reliably on some historical systems. unexpected results would occur if such a string expression were used and $1 expanded to '!', '(', or a known unary primary. the better constructs are:

test -n "$1"
test -z "$1"

respectively. ๐Ÿ’…

Historical systems have also been unreliable given the common construct:

test "$response" = "expected string"

One of the following is a more reliable form:

test "X$response" = "Xexpected string"
test "expected string" = "$response"

Note that the second form assumes that expected string could not be confused with any unary primary. If expected string starts with '-', '(', '!', or even '=', the first form should be used instead. Using the preceding rules without the XSI marked extensions, any of the three comparison forms is reliable, given any input. (However โ€” note that the strings are quoted in all cases.) ๐ŸŽ€

Because the string comparison binary primaries, '=' and "!=", have a higher precedence than any unary primary in the greater than 4 argument case, unexpected results can occur if arguments are not properly prepared. For example, in:

test -d $1 -o -d $2

If $1 evaluates to a possible directory name of '=', the first three arguments are considered a string comparison, which shall cause a syntax error when the second -d is encountered. One of the following forms prevents this; the second is preferred:

test \( -d "$1" \) -o \( -d "$2" \)
test -d "$1" || test -d "$2"

Also in the greater than 4 argument case:

test "$1" = "bat" -a "$2" = "ball"

syntax errors occur if $1 evaluates to '(' or '!'. One of the following forms prevents this; the third is preferred:

test "X$1" = "Xbat" -a "X$2" = "Xball"
test "$1" = "bat" && test "$2" = "ball"
test "X$1" = "Xbat" && test "X$2" = "Xball"

Note that none of the following examples are permitted by the syntax described:

[-f file]
[-f file ]
[ -f file]
[ -f file
test -f file ]

In the first two cases, if a utility named [โ€f exists, that utility would be invoked, and not test. In the remaining cases, the brackets are mismatched, and the behavior is unspecified. ๐Ÿšจ

However:

test ! ]

does have a defined meaning, and must exit with status 1. Similarly:

test ]

must exit with status 0. iconic behavior, honestly โœจ


โœจ EXAMPLES โœจ

  1. Exit if there are not two or three arguments (two variations):
if [ $# -ne 2 ] && [ $# -ne 3 ]; then exit 1; fi
if [ $# -lt 2 ] || [ $# -gt 3 ]; then exit 1; fi
  1. Perform a mkdir if a directory does not exist:
test ! -d tempdir && mkdir tempdir
  1. Wait for a file to become non-readable:
while test -r thefile
do
    sleep 30
done
echo '"thefile" is no longer readable'
  1. Perform a command if the argument is one of three strings (two variations):
if [ "$1" = "pear" ] || [ "$1" = "grape" ] || [ "$1" = "apple" ]
then
    command
fi
case "$1" in
    pear|grape|apple) command ;;
esac

and that's the examples bestie, go forth and test responsibly ๐Ÿ’–

๐Ÿ’ญ RATIONALE ๐Ÿ’ญ

okay bestie, storytime, because the lore here is chef's kiss ๐Ÿ“–โœจ

So the KornShell-derived conditional command โ€” you know, the double bracket [[ ]] โ€” got removed from the shell command language description in an early proposal. And the objections came in HOT: the real problem, they said, is people misusing the test command ([), and putting a whole new thing into the shell is just the wrong way to fix that. Instead, proper documentation plus a new shell reserved word (!) is genuinely sufficient. and honestly? they ate. ๐Ÿ’…


Tests that require multiple test operations can be done at the shell level using individual invocations of the test command and shell logicals, rather than using the error-prone -o flag of test. ๐Ÿ™ˆ no cap.

XSI-conformant systems support more than four arguments.

XSI-conformant systems also support the combining of primaries with the following constructs:

  • expression1 -a expression2 โ€” true if both expression1 and expression2 are true ๐Ÿ’–
  • expression1 -o expression2 โ€” true if at least one of expression1 and expression2 is true โœจ
  • ( expression ) โ€” true if expression is true ๐Ÿซถ

And when you're evaluating these more complex combined expressions, here's the precedence tea โ˜• so you don't get played:

  • The unary primaries have higher precedence than the algebraic binary primaries.
  • The unary primaries have lower precedence than the string binary primaries.
  • The unary and binary primaries have higher precedence than the unary string primary.
  • The ! operator has higher precedence than the -a operator, and the -a operator has higher precedence than the -o operator.
  • The -a and -o operators are left associative.
  • The parentheses can be used to alter the normal precedence and associativity.

Now listen, the BSD and System V versions of -f are not the same, and this matters. The BSD definition was:

  • -f file โ€” true if file exists and is not a directory.

But the SVID version (true if the file exists and is a regular file) was chosen for this volume of POSIX.1-2017, because its use is consistent with the -b, -c, -d, and -p operands (file exists and is a specific file type). periodt. ๐ŸŽ€

The -e primary โ€” which has similar functionality to what the C shell provides โ€” was added because it gives you the only way for a shell script to find out if a file exists without trying to open the file. And since implementations are allowed to add additional file types, a portable script cannot use:

test -b foo -o -c foo -o -d foo -o -f foo -o -p foo

to find out if foo is an existing file. On historical BSD systems, the existence of a file could be determined by:

test -f foo -o -d foo

but there was no easy way to determine that an existing file was a regular file. ๐Ÿ˜ญ An early proposal used the KornShell -a primary (with the same meaning), but this got changed to -e because there were concerns about the high probability of humans confusing the -a primary with the -a binary operator. honestly fair, we would all have done that.

The following options were not included in this volume of POSIX.1-2017, although they are provided by some implementations. These operands should not be used by new implementations for other purposes:

  • -k file โ€” true if file exists and its sticky bit is set.
  • -C file โ€” true if file is a contiguous file.
  • -V file โ€” true if file is a version file.

The following option was not included because it was undocumented in most implementations, has been removed from some implementations (including System V), and the functionality is provided by the shell (see Section 2.6.2, Parameter Expansion):

  • -l string โ€” the length of the string string.

The -b, -c, -g, -p, -u, and -x operands are derived from the SVID; historical BSD does not provide them. The -k operand is derived from System V; historical BSD does not provide it.

On historical BSD systems, test -w directory always returned false, because test tried to open the directory for writing โ€” which always fails. ๐Ÿ’€ iconic behaviour, truly.

Some additional primaries โ€” newly invented or from the KornShell โ€” appeared in an early proposal as part of the conditional command ([[ ]]): s1 > s2, s1 < s2, str = pattern, str != pattern, f1 -nt f2, f1 -ot f2, and f1 -ef f2. They were not carried forward into the test utility when the conditional command was removed from the shell, because they have not been included in the test utility built into historical implementations of the sh utility.

The -t file_descriptor primary is shown with a mandatory argument because the grammar is ambiguous if it can be omitted. Historical implementations have allowed it to be omitted, providing a default of 1.

And one last lil note: [ is not part of the portable filename character set; however, since it is required to be encoded by a single byte, and is part of the portable character set, the name of this utility forms a character string across all supported locales. ๐ŸŒˆ tiny, but mighty.


๐Ÿ”ฎ FUTURE DIRECTIONS ๐Ÿ”ฎ

None. ๐Ÿฆ‹ nothing on the horizon, this is the whole vibe, we're done here bestie.


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

  • Section 1.1.1.4, File Read, Write, and Creation, find
  • The Base Definitions volume of POSIX.1-2017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


and that's a wrap on TEST(1POSIX) ๐Ÿซถ this whole page came from IEEE/The Open Group, 2017, and honestly? iconic of them. thanks for reading the whole thing bestie, you're a real one ๐Ÿ’–โœจ๐ŸŽ€

๐Ÿ“ฆ where this page comes from