1 /* GNU test program (ksb and mjb) */
3 /* Modified to run with the GNU shell by bfox. */
5 /* Copyright (C) 1987-2005 Free Software Foundation, Inc.
7 This file is part of GNU Bash, the Bourne Again SHell.
9 Bash is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
14 Bash is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software Foundation,
21 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
23 /* Define TEST_STANDALONE to get the /bin/test version. Otherwise, you get
24 the shell builtin version. */
28 #include <sys/types.h>
30 #define TEST_STANDALONE 1
36 /* The official name of this program (e.g., no `g' prefix). */
38 # define PROGRAM_NAME "["
40 # define PROGRAM_NAME "test"
45 #include "euidaccess.h"
48 #ifndef _POSIX_VERSION
49 # include <sys/param.h>
50 #endif /* _POSIX_VERSION */
51 #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
52 #define digit(c) ((c) >= '0' && (c) <= '9')
53 #define digit_value(c) ((c) - '0')
57 #if !defined (_POSIX_VERSION)
58 # include <sys/file.h>
59 #endif /* !_POSIX_VERSION */
61 extern gid_t getegid ();
62 extern uid_t geteuid ();
64 /* Exit status for syntax errors, etc. */
65 enum { TEST_TRUE, TEST_FALSE, TEST_FAILURE };
67 #if defined (TEST_STANDALONE)
68 # define test_exit(val) exit (val)
70 static jmp_buf test_exit_buf;
71 static int test_error_return = 0;
72 # define test_exit(val) test_error_return = val, longjmp (test_exit_buf, 1)
73 #endif /* !TEST_STANDALONE */
75 static int pos; /* The offset of the current argument in ARGV. */
76 static int argc; /* The number of arguments present in ARGV. */
77 static char **argv; /* The argument list. */
79 static bool test_unop (char const *s);
80 static bool unary_operator (void);
81 static bool binary_operator (bool);
82 static bool two_arguments (void);
83 static bool three_arguments (void);
84 static bool posixtest (int);
86 static bool expr (void);
87 static bool term (void);
88 static bool and (void);
89 static bool or (void);
91 static void test_syntax_error (char const *format, char const *arg)
93 static void beyond (void) ATTRIBUTE_NORETURN;
96 test_syntax_error (char const *format, char const *arg)
98 fprintf (stderr, "%s: ", argv[0]);
99 fprintf (stderr, format, arg);
101 test_exit (TEST_FAILURE);
104 /* Increment our position in the argument list. Check that we're not
105 past the end of the argument list. This check is supressed if the
106 argument is false. */
113 if (f && pos >= argc)
125 * beyond - call when we're beyond the end of the argument list (an
131 test_syntax_error (_("missing argument after %s"), quote (argv[argc - 1]));
134 /* Syntax error for when an integer argument was expected, but
135 something else was found. */
137 integer_expected_error (char const *pch)
139 test_syntax_error (_("%s: integer expression expected\n"), pch);
142 /* Return true if the characters pointed to by STRING constitute a
143 valid number. Stuff the converted number into RESULT if RESULT is
146 is_int (char const *string, intmax_t *result)
150 char const *orig_string;
158 /* Skip leading whitespace characters. */
159 while (whitespace (*string))
165 /* Save a pointer to the start, for diagnostics. */
166 orig_string = string;
168 /* We allow leading `-' or `+'. */
169 if (*string == '-' || *string == '+')
171 if (!digit (string[1]))
180 while (digit (*string))
184 intmax_t new_v = 10 * value + sign * (*string - '0');
186 ? (INTMAX_MAX / 10 < value || new_v < 0)
187 : (value < INTMAX_MIN / 10 || 0 < new_v))
188 test_syntax_error ((0 < sign
189 ? _("integer is too large: %s\n")
190 : _("integer is too small: %s\n")),
197 /* Skip trailing whitespace, if any. */
198 while (whitespace (*string))
201 /* Error if not at end of string. */
211 /* Find the modification time of FILE, and stuff it into *AGE.
212 Return true if successful. */
214 age_of (char const *filename, time_t *age)
217 bool ok = (stat (filename, &finfo) == 0);
219 *age = finfo.st_mtime;
223 /* Return true if S is one of the test command's binary operators. */
225 binop (char const *s)
227 return ((STREQ (s, "=")) || (STREQ (s, "!=")) || (STREQ (s, "-nt")) ||
228 (STREQ (s, "-ot")) || (STREQ (s, "-ef")) || (STREQ (s, "-eq")) ||
229 (STREQ (s, "-ne")) || (STREQ (s, "-lt")) || (STREQ (s, "-le")) ||
230 (STREQ (s, "-gt")) || (STREQ (s, "-ge")));
234 * term - parse a term and return 1 or 0 depending on whether the term
235 * evaluates to true or false, respectively.
238 * '-'('h'|'d'|'f'|'r'|'s'|'w'|'c'|'b'|'p'|'u'|'g'|'k') filename
239 * '-'('L'|'x') filename
241 * '-'('z'|'n') string
243 * string ('!='|'=') string
244 * <int> '-'(eq|ne|le|lt|ge|gt) <int>
245 * file '-'(nt|ot|ef) file
249 * positive and negative integers
255 bool negated = false;
257 /* Deal with leading `not's. */
258 while (pos < argc && argv[pos][0] == '!' && argv[pos][1] == '\0')
267 /* A paren-bracketed argument. */
268 if (argv[pos][0] == '(' && argv[pos][1] == '\0')
275 pos + nargs < argc && ! STREQ (argv[pos + nargs], ")");
283 value = posixtest (nargs);
285 test_syntax_error (_("')' expected\n"), NULL);
287 if (argv[pos][0] != ')' || argv[pos][1])
288 test_syntax_error (_("')' expected, found %s\n"), argv[pos]);
292 /* Are there enough arguments left that this could be dyadic? */
293 else if (4 <= argc - pos && STREQ (argv[pos], "-l") && binop (argv[pos + 2]))
294 value = binary_operator (true);
295 else if (3 <= argc - pos && binop (argv[pos + 1]))
296 value = binary_operator (false);
298 /* It might be a switch type argument. */
299 else if (argv[pos][0] == '-' && argv[pos][1] && argv[pos][2] == '\0')
301 if (test_unop (argv[pos]))
302 value = unary_operator ();
304 test_syntax_error (_("%s: unary operator expected\n"), argv[pos]);
308 value = (argv[pos][0] != '\0');
312 return negated ^ value;
316 binary_operator (bool l_is_l)
319 struct stat stat_buf, stat_spare;
321 /* Is the right integer expression of the form '-l string'? */
328 if ((op < argc - 2) && STREQ (argv[op + 1], "-l"))
336 if (argv[op][0] == '-')
338 /* check for eq, nt, and stuff */
345 if (argv[op][2] == 't' && !argv[op][3])
349 l = strlen (argv[op - 1]);
352 if (!is_int (argv[op - 1], &l))
353 integer_expected_error (_("before -lt"));
357 r = strlen (argv[op + 2]);
360 if (!is_int (argv[op + 1], &r))
361 integer_expected_error (_("after -lt"));
367 if (argv[op][2] == 'e' && !argv[op][3])
371 l = strlen (argv[op - 1]);
374 if (!is_int (argv[op - 1], &l))
375 integer_expected_error (_("before -le"));
378 r = strlen (argv[op + 2]);
381 if (!is_int (argv[op + 1], &r))
382 integer_expected_error (_("after -le"));
390 if (argv[op][2] == 't' && !argv[op][3])
392 /* gt integer greater than */
394 l = strlen (argv[op - 1]);
397 if (!is_int (argv[op - 1], &l))
398 integer_expected_error (_("before -gt"));
401 r = strlen (argv[op + 2]);
404 if (!is_int (argv[op + 1], &r))
405 integer_expected_error (_("after -gt"));
411 if (argv[op][2] == 'e' && !argv[op][3])
413 /* ge - integer greater than or equal to */
415 l = strlen (argv[op - 1]);
418 if (!is_int (argv[op - 1], &l))
419 integer_expected_error (_("before -ge"));
422 r = strlen (argv[op + 2]);
425 if (!is_int (argv[op + 1], &r))
426 integer_expected_error (_("after -ge"));
434 if (argv[op][2] == 't' && !argv[op][3])
436 /* nt - newer than */
441 test_syntax_error (_("-nt does not accept -l\n"), NULL);
442 le = age_of (argv[op - 1], <);
443 re = age_of (argv[op + 1], &rt);
444 return le > re || (le && lt > rt);
447 if (argv[op][2] == 'e' && !argv[op][3])
449 /* ne - integer not equal */
451 l = strlen (argv[op - 1]);
454 if (!is_int (argv[op - 1], &l))
455 integer_expected_error (_("before -ne"));
458 r = strlen (argv[op + 2]);
461 if (!is_int (argv[op + 1], &r))
462 integer_expected_error (_("after -ne"));
470 if (argv[op][2] == 'q' && !argv[op][3])
472 /* eq - integer equal */
474 l = strlen (argv[op - 1]);
477 if (!is_int (argv[op - 1], &l))
478 integer_expected_error (_("before -eq"));
481 r = strlen (argv[op + 2]);
484 if (!is_int (argv[op + 1], &r))
485 integer_expected_error (_("after -eq"));
491 if (argv[op][2] == 'f' && !argv[op][3])
493 /* ef - hard link? */
496 test_syntax_error (_("-ef does not accept -l\n"), NULL);
497 return (stat (argv[op - 1], &stat_buf) == 0
498 && stat (argv[op + 1], &stat_spare) == 0
499 && stat_buf.st_dev == stat_spare.st_dev
500 && stat_buf.st_ino == stat_spare.st_ino);
505 if ('t' == argv[op][2] && '\000' == argv[op][3])
507 /* ot - older than */
512 test_syntax_error (_("-ot does not accept -l\n"), NULL);
513 le = age_of (argv[op - 1], <);
514 re = age_of (argv[op + 1], &rt);
515 return le < re || (re && lt < rt);
520 /* FIXME: is this dead code? */
521 test_syntax_error (_("unknown binary operator\n"), argv[op]);
524 if (argv[op][0] == '=' && !argv[op][1])
526 bool value = STREQ (argv[pos], argv[pos + 2]);
531 if (STREQ (argv[op], "!="))
533 bool value = !STREQ (argv[pos], argv[pos + 2]);
543 unary_operator (void)
545 struct stat stat_buf;
547 switch (argv[pos][1])
552 /* All of the following unary operators use unary_advance (), which
553 checks to make sure that there is an argument, and then advances
554 pos right past it. This means that pos - 1 is the location of the
557 case 'a': /* file exists in the file system? */
560 return stat (argv[pos - 1], &stat_buf) == 0;
562 case 'r': /* file is readable? */
564 return euidaccess (argv[pos - 1], R_OK) == 0;
566 case 'w': /* File is writable? */
568 return euidaccess (argv[pos - 1], W_OK) == 0;
570 case 'x': /* File is executable? */
572 return euidaccess (argv[pos - 1], X_OK) == 0;
574 case 'O': /* File is owned by you? */
576 return (stat (argv[pos - 1], &stat_buf) == 0
577 && (geteuid () == stat_buf.st_uid));
579 case 'G': /* File is owned by your group? */
581 return (stat (argv[pos - 1], &stat_buf) == 0
582 && (getegid () == stat_buf.st_gid));
584 case 'f': /* File is a file? */
586 /* Under POSIX, -f is true if the given file exists
587 and is a regular file. */
588 return (stat (argv[pos - 1], &stat_buf) == 0
589 && S_ISREG (stat_buf.st_mode));
591 case 'd': /* File is a directory? */
593 return (stat (argv[pos - 1], &stat_buf) == 0
594 && S_ISDIR (stat_buf.st_mode));
596 case 's': /* File has something in it? */
598 return (stat (argv[pos - 1], &stat_buf) == 0
599 && 0 < stat_buf.st_size);
601 case 'S': /* File is a socket? */
603 return (stat (argv[pos - 1], &stat_buf) == 0
604 && S_ISSOCK (stat_buf.st_mode));
606 case 'c': /* File is character special? */
608 return (stat (argv[pos - 1], &stat_buf) == 0
609 && S_ISCHR (stat_buf.st_mode));
611 case 'b': /* File is block special? */
613 return (stat (argv[pos - 1], &stat_buf) == 0
614 && S_ISBLK (stat_buf.st_mode));
616 case 'p': /* File is a named pipe? */
618 return (stat (argv[pos - 1], &stat_buf) == 0
619 && S_ISFIFO (stat_buf.st_mode));
621 case 'L': /* Same as -h */
624 case 'h': /* File is a symbolic link? */
626 return (lstat (argv[pos - 1], &stat_buf) == 0
627 && S_ISLNK (stat_buf.st_mode));
629 case 'u': /* File is setuid? */
631 return (stat (argv[pos - 1], &stat_buf) == 0
632 && (stat_buf.st_mode & S_ISUID));
634 case 'g': /* File is setgid? */
636 return (stat (argv[pos - 1], &stat_buf) == 0
637 && (stat_buf.st_mode & S_ISGID));
639 case 'k': /* File has sticky bit set? */
641 return (stat (argv[pos - 1], &stat_buf) == 0
642 && (stat_buf.st_mode & S_ISVTX));
644 case 't': /* File (fd) is a terminal? */
648 if (!is_int (argv[pos - 1], &fd))
649 integer_expected_error (_("after -t"));
650 return INT_MIN <= fd && fd <= INT_MAX && isatty (fd);
653 case 'n': /* True if arg has some length. */
655 return argv[pos - 1][0] != 0;
657 case 'z': /* True if arg has no length. */
659 return argv[pos - 1][0] == '\0';
676 if (! (pos < argc && STREQ (argv[pos], "-a")))
695 if (! (pos < argc && STREQ (argv[pos], "-o")))
711 return or (); /* Same with this. */
714 /* Return true if OP is one of the test command's unary operators. */
716 test_unop (char const *op)
723 case 'a': case 'b': case 'c': case 'd': case 'e':
724 case 'f': case 'g': case 'h': case 'k': case 'n':
725 case 'o': case 'p': case 'r': case 's': case 't':
726 case 'u': case 'w': case 'x': case 'z':
727 case 'G': case 'L': case 'O': case 'S': case 'N':
737 return argv[pos++][0] != '\0';
745 if (STREQ (argv[pos], "!"))
748 value = ! one_argument ();
750 else if (argv[pos][0] == '-'
751 && argv[pos][1] != '\0'
752 && argv[pos][2] == '\0')
754 if (test_unop (argv[pos]))
755 value = unary_operator ();
757 test_syntax_error (_("%s: unary operator expected\n"), argv[pos]);
765 three_arguments (void)
769 if (binop (argv[pos + 1]))
770 value = binary_operator (false);
771 else if (STREQ (argv[pos], "!"))
774 value = !two_arguments ();
776 else if (STREQ (argv[pos], "(") && STREQ (argv[pos + 2], ")"))
779 value = one_argument ();
782 else if (STREQ (argv[pos + 1], "-a") || STREQ (argv[pos + 1], "-o"))
785 test_syntax_error (_("%s: binary operator expected\n"), argv[pos+1]);
789 /* This is an implementation of a Posix.2 proposal by David Korn. */
791 posixtest (int nargs)
798 value = one_argument ();
802 value = two_arguments ();
806 value = three_arguments ();
810 if (STREQ (argv[pos], "!"))
813 value = !three_arguments ();
816 if (STREQ (argv[pos], "(") && STREQ (argv[pos + 3], ")"))
819 value = two_arguments ();
834 #if defined (TEST_STANDALONE)
835 # include "long-options.h"
840 if (status != EXIT_SUCCESS)
841 fprintf (stderr, _("Try `%s --help' for more information.\n"),
846 Usage: test EXPRESSION\n\
848 or: [ EXPRESSION ]\n\
853 Exit with the status determined by EXPRESSION.\n\
856 fputs (HELP_OPTION_DESCRIPTION, stdout);
857 fputs (VERSION_OPTION_DESCRIPTION, stdout);
860 An omitted EXPRESSION defaults to false. Otherwise,\n\
861 EXPRESSION is true or false and sets exit status. It is one of:\n\
865 ( EXPRESSION ) EXPRESSION is true\n\
866 ! EXPRESSION EXPRESSION is false\n\
867 EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true\n\
868 EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true\n\
872 -n STRING the length of STRING is nonzero\n\
873 STRING equivalent to -n STRING\n\
874 -z STRING the length of STRING is zero\n\
875 STRING1 = STRING2 the strings are equal\n\
876 STRING1 != STRING2 the strings are not equal\n\
880 INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2\n\
881 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2\n\
882 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2\n\
883 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2\n\
884 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2\n\
885 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2\n\
889 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers\n\
890 FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2\n\
891 FILE1 -ot FILE2 FILE1 is older than FILE2\n\
895 -b FILE FILE exists and is block special\n\
896 -c FILE FILE exists and is character special\n\
897 -d FILE FILE exists and is a directory\n\
898 -e FILE FILE exists\n\
901 -f FILE FILE exists and is a regular file\n\
902 -g FILE FILE exists and is set-group-ID\n\
903 -G FILE FILE exists and is owned by the effective group ID\n\
904 -h FILE FILE exists and is a symbolic link (same as -L)\n\
905 -k FILE FILE exists and has its sticky bit set\n\
908 -L FILE FILE exists and is a symbolic link (same as -h)\n\
909 -O FILE FILE exists and is owned by the effective user ID\n\
910 -p FILE FILE exists and is a named pipe\n\
911 -r FILE FILE exists and read permission is granted\n\
912 -s FILE FILE exists and has a size greater than zero\n\
915 -S FILE FILE exists and is a socket\n\
916 -t FD file descriptor FD is opened on a terminal\n\
917 -u FILE FILE exists and its set-user-ID bit is set\n\
918 -w FILE FILE exists and write permission is granted\n\
919 -x FILE FILE exists and execute (or search) permission is granted\n\
923 Except for -h and -L, all FILE-related tests dereference symbolic links.\n\
924 Beware that parentheses need to be escaped (e.g., by backslashes) for shells.\n\
925 INTEGER may also be -l STRING, which evaluates to the length of STRING.\n\
927 printf (USAGE_BUILTIN_WARNING, _("test and/or ["));
928 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
932 #endif /* TEST_STANDALONE */
934 #if !defined (TEST_STANDALONE)
935 # define main test_command
938 #define AUTHORS "Kevin Braunsdorf", "Matthew Bradburn"
947 main (int margc, char **margv)
951 #if !defined (TEST_STANDALONE)
954 code = setjmp (test_exit_buf);
957 return (test_error_return);
958 #else /* TEST_STANDALONE */
959 initialize_main (&margc, &margv);
960 program_name = margv[0];
961 setlocale (LC_ALL, "");
962 bindtextdomain (PACKAGE, LOCALEDIR);
963 textdomain (PACKAGE);
965 initialize_exit_failure (TEST_FAILURE);
966 atexit (close_stdout);
967 #endif /* TEST_STANDALONE */
973 /* Recognize --help or --version, but only when invoked in the
974 "[" form, and when the last argument is not "]". POSIX
975 allows "[ --help" and "[ --version" to have the usual GNU
976 behavior, but it requires "test --help" and "test --version"
977 to exit silently with status 1. */
978 if (margc < 2 || !STREQ (margv[margc - 1], "]"))
980 parse_long_options (margc, margv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
981 usage, AUTHORS, (char const *) NULL);
982 test_syntax_error (_("missing `]'\n"), NULL);
992 test_exit (TEST_FALSE);
994 value = posixtest (argc - 1);
997 test_syntax_error (_("extra argument %s"), quote (argv[pos]));
999 test_exit (value ? TEST_TRUE : TEST_FALSE);