1 /* GNU test program (ksb and mjb) */
3 /* Modified to run with the GNU shell by bfox. */
5 /* Copyright (C) 1987-2024 Free Software Foundation, Inc.
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 /* Define TEST_STANDALONE to get the /bin/test version. Otherwise, you get
21 the shell builtin version. */
26 #include <sys/types.h>
28 #define TEST_STANDALONE 1
34 /* The official name of this program (e.g., no 'g' prefix). */
36 # define PROGRAM_NAME "["
38 # define PROGRAM_NAME "test"
44 #include "stat-time.h"
45 #include "strnumcmp.h"
51 # include <sys/param.h>
54 /* Exit status for syntax errors, etc. */
55 enum { TEST_TRUE
, TEST_FALSE
, TEST_FAILURE
};
57 #if defined TEST_STANDALONE
58 # define test_exit(val) exit (val)
59 # define test_main_return(val) return val
61 static jmp_buf test_exit_buf
;
62 static int test_error_return
= 0;
63 # define test_exit(val) test_error_return = val, longjmp (test_exit_buf, 1)
64 # define test_main_return(val) test_exit (val)
65 #endif /* !TEST_STANDALONE */
67 static int pos
; /* The offset of the current argument in ARGV. */
68 static int argc
; /* The number of arguments present in ARGV. */
69 static char **argv
; /* The argument list. */
71 static bool unary_operator (void);
72 static bool binary_operator (bool);
73 static bool two_arguments (void);
74 static bool three_arguments (void);
75 static bool posixtest (int);
77 static bool expr (void);
78 static bool term (void);
79 static bool and (void);
80 static bool or (void);
82 static void beyond (void);
84 ATTRIBUTE_FORMAT ((printf
, 1, 2))
86 test_syntax_error (char const *format
, ...)
89 va_start (ap
, format
);
90 verror (0, 0, format
, ap
);
91 test_exit (TEST_FAILURE
);
94 /* Increment our position in the argument list. Check that we're not
95 past the end of the argument list. This check is suppressed if the
103 if (f
&& pos
>= argc
)
115 * beyond - call when we're beyond the end of the argument list (an
118 static _Noreturn
void
121 test_syntax_error (_("missing argument after %s"), quote (argv
[argc
- 1]));
124 /* If the characters pointed to by STRING constitute a valid number,
125 return a pointer to the start of the number, skipping any blanks or
126 leading '+'. Otherwise, report an error and exit. */
128 find_int (char const *string
)
131 char const *number_start
;
133 for (p
= string
; isspace (to_uchar (*p
)); p
++)
151 while (isspace (to_uchar (*p
)))
157 test_syntax_error (_("invalid integer %s"), quote (string
));
160 /* Find the modification time of FILE, and stuff it into *MTIME.
161 Return true if successful. */
163 get_mtime (char const *filename
, struct timespec
*mtime
)
166 bool ok
= (stat (filename
, &finfo
) == 0);
168 *mtime
= get_stat_mtime (&finfo
);
172 /* Return true if S is one of the test command's binary operators. */
174 binop (char const *s
)
176 return ((STREQ (s
, "=")) || (STREQ (s
, "!=")) || (STREQ (s
, "==")) ||
177 (STREQ (s
, "-nt")) ||
178 (STREQ (s
, "-ot")) || (STREQ (s
, "-ef")) || (STREQ (s
, "-eq")) ||
179 (STREQ (s
, "-ne")) || (STREQ (s
, "-lt")) || (STREQ (s
, "-le")) ||
180 (STREQ (s
, "-gt")) || (STREQ (s
, "-ge")));
184 * term - parse a term and return 1 or 0 depending on whether the term
185 * evaluates to true or false, respectively.
188 * '-'('h'|'d'|'f'|'r'|'s'|'w'|'c'|'b'|'p'|'u'|'g'|'k') filename
189 * '-'('L'|'x') filename
191 * '-'('z'|'n') string
193 * string ('!='|'=') string
194 * <int> '-'(eq|ne|le|lt|ge|gt) <int>
195 * file '-'(nt|ot|ef) file
199 * positive and negative integers
205 bool negated
= false;
207 /* Deal with leading 'not's. */
208 while (pos
< argc
&& argv
[pos
][0] == '!' && argv
[pos
][1] == '\0')
217 /* A paren-bracketed argument. */
218 if (argv
[pos
][0] == '(' && argv
[pos
][1] == '\0')
225 pos
+ nargs
< argc
&& ! STREQ (argv
[pos
+ nargs
], ")");
233 value
= posixtest (nargs
);
235 test_syntax_error (_("%s expected"), quote (")"));
237 if (argv
[pos
][0] != ')' || argv
[pos
][1])
238 test_syntax_error (_("%s expected, found %s"),
239 quote_n (0, ")"), quote_n (1, argv
[pos
]));
243 /* Are there enough arguments left that this could be dyadic? */
244 else if (4 <= argc
- pos
&& STREQ (argv
[pos
], "-l") && binop (argv
[pos
+ 2]))
245 value
= binary_operator (true);
246 else if (3 <= argc
- pos
&& binop (argv
[pos
+ 1]))
247 value
= binary_operator (false);
249 /* It might be a switch type argument. */
250 else if (argv
[pos
][0] == '-' && argv
[pos
][1] && argv
[pos
][2] == '\0')
251 value
= unary_operator ();
254 value
= (argv
[pos
][0] != '\0');
258 return negated
^ value
;
262 binary_operator (bool l_is_l
)
265 struct stat stat_buf
, stat_spare
;
266 /* Is the right integer expression of the form '-l string'? */
273 if ((op
< argc
- 2) && STREQ (argv
[op
+ 1], "-l"))
281 if (argv
[op
][0] == '-')
283 /* check for eq, nt, and stuff */
284 if ((((argv
[op
][1] == 'l' || argv
[op
][1] == 'g')
285 && (argv
[op
][2] == 'e' || argv
[op
][2] == 't'))
286 || (argv
[op
][1] == 'e' && argv
[op
][2] == 'q')
287 || (argv
[op
][1] == 'n' && argv
[op
][2] == 'e'))
290 char lbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
291 char rbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
292 char const *l
= (l_is_l
293 ? umaxtostr (strlen (argv
[op
- 1]), lbuf
)
294 : find_int (argv
[op
- 1]));
295 char const *r
= (r_is_l
296 ? umaxtostr (strlen (argv
[op
+ 2]), rbuf
)
297 : find_int (argv
[op
+ 1]));
298 int cmp
= strintcmp (l
, r
);
299 bool xe_operator
= (argv
[op
][2] == 'e');
301 return (argv
[op
][1] == 'l' ? cmp
< xe_operator
302 : argv
[op
][1] == 'g' ? cmp
> - xe_operator
303 : (cmp
!= 0) == xe_operator
);
312 if (argv
[op
][2] == 't' && !argv
[op
][3])
314 /* nt - newer than */
315 struct timespec lt
, rt
;
318 if (l_is_l
|| r_is_l
)
319 test_syntax_error (_("-nt does not accept -l"));
320 le
= get_mtime (argv
[op
- 1], <
);
321 re
= get_mtime (argv
[op
+ 1], &rt
);
322 return le
&& (!re
|| timespec_cmp (lt
, rt
) > 0);
327 if (argv
[op
][2] == 'f' && !argv
[op
][3])
329 /* ef - hard link? */
331 if (l_is_l
|| r_is_l
)
332 test_syntax_error (_("-ef does not accept -l"));
333 return (stat (argv
[op
- 1], &stat_buf
) == 0
334 && stat (argv
[op
+ 1], &stat_spare
) == 0
335 && stat_buf
.st_dev
== stat_spare
.st_dev
336 && stat_buf
.st_ino
== stat_spare
.st_ino
);
341 if ('t' == argv
[op
][2] && '\000' == argv
[op
][3])
343 /* ot - older than */
344 struct timespec lt
, rt
;
347 if (l_is_l
|| r_is_l
)
348 test_syntax_error (_("-ot does not accept -l"));
349 le
= get_mtime (argv
[op
- 1], <
);
350 re
= get_mtime (argv
[op
+ 1], &rt
);
351 return re
&& (!le
|| timespec_cmp (lt
, rt
) < 0);
356 /* FIXME: is this dead code? */
357 test_syntax_error (_("%s: unknown binary operator"), quote (argv
[op
]));
360 if (argv
[op
][0] == '='
361 && (!argv
[op
][1] || ((argv
[op
][1] == '=') && !argv
[op
][2])))
363 bool value
= STREQ (argv
[pos
], argv
[pos
+ 2]);
368 if (STREQ (argv
[op
], "!="))
370 bool value
= !STREQ (argv
[pos
], argv
[pos
+ 2]);
380 unary_operator (void)
382 struct stat stat_buf
;
384 switch (argv
[pos
][1])
387 test_syntax_error (_("%s: unary operator expected"), quote (argv
[pos
]));
389 /* All of the following unary operators use unary_advance (), which
390 checks to make sure that there is an argument, and then advances
391 pos right past it. This means that pos - 1 is the location of the
394 case 'e': /* file exists in the file system? */
396 return stat (argv
[pos
- 1], &stat_buf
) == 0;
398 case 'r': /* file is readable? */
400 return euidaccess (argv
[pos
- 1], R_OK
) == 0;
402 case 'w': /* File is writable? */
404 return euidaccess (argv
[pos
- 1], W_OK
) == 0;
406 case 'x': /* File is executable? */
408 return euidaccess (argv
[pos
- 1], X_OK
) == 0;
410 case 'N': /* File exists and has been modified since it was last read? */
413 if (stat (argv
[pos
- 1], &stat_buf
) != 0)
415 struct timespec atime
= get_stat_atime (&stat_buf
);
416 struct timespec mtime
= get_stat_mtime (&stat_buf
);
417 return (timespec_cmp (mtime
, atime
) > 0);
420 case 'O': /* File is owned by you? */
423 if (stat (argv
[pos
- 1], &stat_buf
) != 0)
426 uid_t euid
= geteuid ();
428 return ! (euid
== NO_UID
&& errno
) && euid
== stat_buf
.st_uid
;
431 case 'G': /* File is owned by your group? */
434 if (stat (argv
[pos
- 1], &stat_buf
) != 0)
437 gid_t egid
= getegid ();
439 return ! (egid
== NO_GID
&& errno
) && egid
== stat_buf
.st_gid
;
442 case 'f': /* File is a file? */
444 /* Under POSIX, -f is true if the given file exists
445 and is a regular file. */
446 return (stat (argv
[pos
- 1], &stat_buf
) == 0
447 && S_ISREG (stat_buf
.st_mode
));
449 case 'd': /* File is a directory? */
451 return (stat (argv
[pos
- 1], &stat_buf
) == 0
452 && S_ISDIR (stat_buf
.st_mode
));
454 case 's': /* File has something in it? */
456 return (stat (argv
[pos
- 1], &stat_buf
) == 0
457 && 0 < stat_buf
.st_size
);
459 case 'S': /* File is a socket? */
461 return (stat (argv
[pos
- 1], &stat_buf
) == 0
462 && S_ISSOCK (stat_buf
.st_mode
));
464 case 'c': /* File is character special? */
466 return (stat (argv
[pos
- 1], &stat_buf
) == 0
467 && S_ISCHR (stat_buf
.st_mode
));
469 case 'b': /* File is block special? */
471 return (stat (argv
[pos
- 1], &stat_buf
) == 0
472 && S_ISBLK (stat_buf
.st_mode
));
474 case 'p': /* File is a named pipe? */
476 return (stat (argv
[pos
- 1], &stat_buf
) == 0
477 && S_ISFIFO (stat_buf
.st_mode
));
479 case 'L': /* Same as -h */
482 case 'h': /* File is a symbolic link? */
484 return (lstat (argv
[pos
- 1], &stat_buf
) == 0
485 && S_ISLNK (stat_buf
.st_mode
));
487 case 'u': /* File is setuid? */
489 return (stat (argv
[pos
- 1], &stat_buf
) == 0
490 && (stat_buf
.st_mode
& S_ISUID
));
492 case 'g': /* File is setgid? */
494 return (stat (argv
[pos
- 1], &stat_buf
) == 0
495 && (stat_buf
.st_mode
& S_ISGID
));
497 case 'k': /* File has sticky bit set? */
499 return (stat (argv
[pos
- 1], &stat_buf
) == 0
500 && (stat_buf
.st_mode
& S_ISVTX
));
502 case 't': /* File (fd) is a terminal? */
507 arg
= find_int (argv
[pos
- 1]);
509 fd
= strtol (arg
, nullptr, 10);
510 return (errno
!= ERANGE
&& 0 <= fd
&& fd
<= INT_MAX
&& isatty (fd
));
513 case 'n': /* True if arg has some length. */
515 return argv
[pos
- 1][0] != 0;
517 case 'z': /* True if arg has no length. */
519 return argv
[pos
- 1][0] == '\0';
536 if (! (pos
< argc
&& STREQ (argv
[pos
], "-a")))
555 if (! (pos
< argc
&& STREQ (argv
[pos
], "-o")))
571 return or (); /* Same with this. */
577 return argv
[pos
++][0] != '\0';
585 if (STREQ (argv
[pos
], "!"))
588 value
= ! one_argument ();
590 else if (argv
[pos
][0] == '-'
591 && argv
[pos
][1] != '\0'
592 && argv
[pos
][2] == '\0')
594 value
= unary_operator ();
602 three_arguments (void)
606 if (binop (argv
[pos
+ 1]))
607 value
= binary_operator (false);
608 else if (STREQ (argv
[pos
], "!"))
611 value
= !two_arguments ();
613 else if (STREQ (argv
[pos
], "(") && STREQ (argv
[pos
+ 2], ")"))
616 value
= one_argument ();
619 else if (STREQ (argv
[pos
+ 1], "-a") || STREQ (argv
[pos
+ 1], "-o"))
622 test_syntax_error (_("%s: binary operator expected"),
623 quote (argv
[pos
+ 1]));
627 /* This is an implementation of a Posix.2 proposal by David Korn. */
629 posixtest (int nargs
)
636 value
= one_argument ();
640 value
= two_arguments ();
644 value
= three_arguments ();
648 if (STREQ (argv
[pos
], "!"))
651 value
= !three_arguments ();
654 if (STREQ (argv
[pos
], "(") && STREQ (argv
[pos
+ 3], ")"))
657 value
= two_arguments ();
671 #if defined TEST_STANDALONE
676 if (status
!= EXIT_SUCCESS
)
681 Usage: test EXPRESSION\n\
683 or: [ EXPRESSION ]\n\
688 Exit with the status determined by EXPRESSION.\n\
691 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
692 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
695 An omitted EXPRESSION defaults to false. Otherwise,\n\
696 EXPRESSION is true or false and sets exit status. It is one of:\n\
700 ( EXPRESSION ) EXPRESSION is true\n\
701 ! EXPRESSION EXPRESSION is false\n\
702 EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true\n\
703 EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true\n\
707 -n STRING the length of STRING is nonzero\n\
708 STRING equivalent to -n STRING\n\
709 -z STRING the length of STRING is zero\n\
710 STRING1 = STRING2 the strings are equal\n\
711 STRING1 != STRING2 the strings are not equal\n\
715 INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2\n\
716 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2\n\
717 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2\n\
718 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2\n\
719 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2\n\
720 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2\n\
724 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers\n\
725 FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2\n\
726 FILE1 -ot FILE2 FILE1 is older than FILE2\n\
730 -b FILE FILE exists and is block special\n\
731 -c FILE FILE exists and is character special\n\
732 -d FILE FILE exists and is a directory\n\
733 -e FILE FILE exists\n\
736 -f FILE FILE exists and is a regular file\n\
737 -g FILE FILE exists and is set-group-ID\n\
738 -G FILE FILE exists and is owned by the effective group ID\n\
739 -h FILE FILE exists and is a symbolic link (same as -L)\n\
740 -k FILE FILE exists and has its sticky bit set\n\
743 -L FILE FILE exists and is a symbolic link (same as -h)\n\
744 -N FILE FILE exists and has been modified since it was last read\n\
745 -O FILE FILE exists and is owned by the effective user ID\n\
746 -p FILE FILE exists and is a named pipe\n\
747 -r FILE FILE exists and the user has read access\n\
748 -s FILE FILE exists and has a size greater than zero\n\
751 -S FILE FILE exists and is a socket\n\
752 -t FD file descriptor FD is opened on a terminal\n\
753 -u FILE FILE exists and its set-user-ID bit is set\n\
754 -w FILE FILE exists and the user has write access\n\
755 -x FILE FILE exists and the user has execute (or search) access\n\
759 Except for -h and -L, all FILE-related tests dereference symbolic links.\n\
760 Beware that parentheses need to be escaped (e.g., by backslashes) for shells.\n\
761 INTEGER may also be -l STRING, which evaluates to the length of STRING.\n\
765 Binary -a and -o are ambiguous. Use 'test EXPR1 && test EXPR2'\n\
766 or 'test EXPR1 || test EXPR2' instead.\n\
770 '[' honors --help and --version, but 'test' treats them as STRINGs.\n\
772 printf (USAGE_BUILTIN_WARNING
, _("test and/or ["));
773 emit_ancillary_info (PROGRAM_NAME
);
777 #endif /* TEST_STANDALONE */
779 #if !defined TEST_STANDALONE
780 # define main test_command
784 proper_name ("Kevin Braunsdorf"), \
785 proper_name ("Matthew Bradburn")
794 main (int margc
, char **margv
)
798 #if !defined TEST_STANDALONE
801 code
= setjmp (test_exit_buf
);
804 return (test_error_return
);
805 #else /* TEST_STANDALONE */
806 initialize_main (&margc
, &margv
);
807 set_program_name (margv
[0]);
808 setlocale (LC_ALL
, "");
809 bindtextdomain (PACKAGE
, LOCALEDIR
);
810 textdomain (PACKAGE
);
812 initialize_exit_failure (TEST_FAILURE
);
813 atexit (close_stdout
);
814 #endif /* TEST_STANDALONE */
820 /* Recognize --help or --version, but only when invoked in the
821 "[" form, when the last argument is not "]". Use direct
822 parsing, rather than parse_long_options, to avoid accepting
823 abbreviations. POSIX allows "[ --help" and "[ --version" to
824 have the usual GNU behavior, but it requires "test --help"
825 and "test --version" to exit silently with status 0. */
828 if (STREQ (margv
[1], "--help"))
829 usage (EXIT_SUCCESS
);
831 if (STREQ (margv
[1], "--version"))
833 version_etc (stdout
, PROGRAM_NAME
, PACKAGE_NAME
, Version
, AUTHORS
,
835 test_main_return (EXIT_SUCCESS
);
838 if (margc
< 2 || !STREQ (margv
[margc
- 1], "]"))
839 test_syntax_error (_("missing %s"), quote ("]"));
848 test_main_return (TEST_FALSE
);
850 value
= posixtest (argc
- 1);
853 test_syntax_error (_("extra argument %s"), quote (argv
[pos
]));
855 test_main_return (value
? TEST_TRUE
: TEST_FALSE
);