1 /* GNU test program (ksb and mjb) */
3 /* Modified to run with the GNU shell by bfox. */
5 /* Copyright (C) 1987-2003 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"
46 #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 ();
71 /* The following few defines control the truth and false output of each stage.
72 TRUE and FALSE are what we use to compute the final output value.
73 SHELL_BOOLEAN is the form which returns truth or falseness in shell terms.
74 TRUTH_OR is how to do logical or with TRUE and FALSE.
75 TRUTH_AND is how to do logical and with TRUE and FALSE..
76 Default is TRUE = 1, FALSE = 0, TRUTH_OR = a | b, TRUTH_AND = a & b,
77 SHELL_BOOLEAN = (!value). */
80 #define SHELL_BOOLEAN(value) (!(value))
81 #define TRUTH_OR(a, b) ((a) | (b))
82 #define TRUTH_AND(a, b) ((a) & (b))
84 /* Exit status for syntax errors, etc. */
85 enum { TEST_FAILURE = 2 };
87 #if defined (TEST_STANDALONE)
88 # define test_exit(val) exit (val)
90 static jmp_buf test_exit_buf;
91 static int test_error_return = 0;
92 # define test_exit(val) test_error_return = val, longjmp (test_exit_buf, 1)
93 #endif /* !TEST_STANDALONE */
95 static int pos; /* The offset of the current argument in ARGV. */
96 static int argc; /* The number of arguments present in ARGV. */
97 static char **argv; /* The argument list. */
99 static int test_unop (char const *s);
100 static int binop (char *s);
101 static int unary_operator (void);
102 static int binary_operator (bool);
103 static int two_arguments (void);
104 static int three_arguments (void);
105 static int posixtest (int);
107 static int expr (void);
108 static int term (void);
109 static int and (void);
110 static int or (void);
112 static void test_syntax_error (char const *format, char const *arg)
114 static void beyond (void) ATTRIBUTE_NORETURN;
117 test_syntax_error (char const *format, char const *arg)
119 fprintf (stderr, "%s: ", argv[0]);
120 fprintf (stderr, format, arg);
122 test_exit (TEST_FAILURE);
125 #if HAVE_SETREUID && HAVE_SETREGID
126 /* Do the same thing access(2) does, but use the effective uid and gid. */
129 eaccess (char const *file, int mode)
132 static uid_t uid, euid;
133 static gid_t gid, egid;
145 /* Set the real user and group IDs to the effective ones. */
147 setreuid (euid, uid);
149 setregid (egid, gid);
151 result = access (file, mode);
155 setreuid (uid, euid);
157 setregid (gid, egid);
162 # define eaccess(F, M) euidaccess (F, M)
165 /* Increment our position in the argument list. Check that we're not
166 past the end of the argument list. This check is supressed if the
167 argument is FALSE. Made a macro for efficiency. */
172 if ((f) && pos >= argc) \
177 #if !defined (advance)
183 if (f && pos >= argc)
188 #define unary_advance() \
197 * beyond - call when we're beyond the end of the argument list (an
203 test_syntax_error (_("argument expected\n"), NULL);
206 /* Syntax error for when an integer argument was expected, but
207 something else was found. */
209 integer_expected_error (char const *pch)
211 test_syntax_error (_("%s: integer expression expected\n"), pch);
214 /* Return nonzero if the characters pointed to by STRING constitute a
215 valid number. Stuff the converted number into RESULT if RESULT is
218 isint (register char *string, intmax_t *result)
229 /* Skip leading whitespace characters. */
230 while (whitespace (*string))
236 /* We allow leading `-' or `+'. */
237 if (*string == '-' || *string == '+')
239 if (!digit (string[1]))
248 while (digit (*string))
251 value = (value * 10) + digit_value (*string);
255 /* Skip trailing whitespace, if any. */
256 while (whitespace (*string))
259 /* Error if not at end of string. */
272 /* Find the modification time of FILE, and stuff it into *AGE.
273 Return 0 if successful, -1 if not. */
275 age_of (char *filename, time_t *age)
278 int r = stat (filename, &finfo);
280 *age = finfo.st_mtime;
285 * term - parse a term and return 1 or 0 depending on whether the term
286 * evaluates to true or false, respectively.
289 * '-'('h'|'d'|'f'|'r'|'s'|'w'|'c'|'b'|'p'|'u'|'g'|'k') filename
290 * '-'('L'|'x') filename
292 * '-'('z'|'n') string
294 * string ('!='|'=') string
295 * <int> '-'(eq|ne|le|lt|ge|gt) <int>
296 * file '-'(nt|ot|ef) file
300 * positive and negative integers
310 /* Deal with leading `not's. */
311 if (argv[pos][0] == '!' && argv[pos][1] == '\0')
314 while (pos < argc && argv[pos][0] == '!' && argv[pos][1] == '\0')
320 return (value ? !term() : term());
323 /* A paren-bracketed argument. */
324 if (argv[pos][0] == '(' && argv[pos][1] == '\0')
331 pos + nargs < argc && ! STREQ (argv[pos + nargs], ")");
339 value = posixtest (nargs);
341 test_syntax_error (_("')' expected\n"), NULL);
343 if (argv[pos][0] != ')' || argv[pos][1])
344 test_syntax_error (_("')' expected, found %s\n"), argv[pos]);
349 /* are there enough arguments left that this could be dyadic? */
350 if (pos + 4 <= argc && STREQ (argv[pos], "-l") && binop (argv[pos + 2]))
351 value = binary_operator (true);
352 else if (pos + 3 <= argc && binop (argv[pos + 1]))
353 value = binary_operator (false);
355 /* Might be a switch type argument */
356 else if (argv[pos][0] == '-' && argv[pos][1] && argv[pos][2] == '\0')
358 if (test_unop (argv[pos]))
359 value = unary_operator ();
361 test_syntax_error (_("%s: unary operator expected\n"), argv[pos]);
365 value = (argv[pos][0] != '\0');
373 binary_operator (bool l_is_l)
376 struct stat stat_buf, stat_spare;
379 /* Is the right integer expression of the form '-l string'? */
386 if ((op < argc - 2) && (strcmp (argv[op + 1], "-l") == 0))
394 if (argv[op][0] == '-')
396 /* check for eq, nt, and stuff */
403 if (argv[op][2] == 't' && !argv[op][3])
407 l = strlen (argv[op - 1]);
410 if (!isint (argv[op - 1], &l))
411 integer_expected_error (_("before -lt"));
415 r = strlen (argv[op + 2]);
418 if (!isint (argv[op + 1], &r))
419 integer_expected_error (_("after -lt"));
422 return (TRUE == (l < r));
425 if (argv[op][2] == 'e' && !argv[op][3])
429 l = strlen (argv[op - 1]);
432 if (!isint (argv[op - 1], &l))
433 integer_expected_error (_("before -le"));
436 r = strlen (argv[op + 2]);
439 if (!isint (argv[op + 1], &r))
440 integer_expected_error (_("after -le"));
443 return (TRUE == (l <= r));
448 if (argv[op][2] == 't' && !argv[op][3])
450 /* gt integer greater than */
452 l = strlen (argv[op - 1]);
455 if (!isint (argv[op - 1], &l))
456 integer_expected_error (_("before -gt"));
459 r = strlen (argv[op + 2]);
462 if (!isint (argv[op + 1], &r))
463 integer_expected_error (_("after -gt"));
466 return (TRUE == (l > r));
469 if (argv[op][2] == 'e' && !argv[op][3])
471 /* ge - integer greater than or equal to */
473 l = strlen (argv[op - 1]);
476 if (!isint (argv[op - 1], &l))
477 integer_expected_error (_("before -ge"));
480 r = strlen (argv[op + 2]);
483 if (!isint (argv[op + 1], &r))
484 integer_expected_error (_("after -ge"));
487 return (TRUE == (l >= r));
492 if (argv[op][2] == 't' && !argv[op][3])
494 /* nt - newer than */
498 if (l_is_l || r_is_l)
499 test_syntax_error (_("-nt does not accept -l\n"), NULL);
500 le = age_of (argv[op - 1], <);
501 re = age_of (argv[op + 1], &rt);
502 return le > re || (le == 0 && lt > rt);
505 if (argv[op][2] == 'e' && !argv[op][3])
507 /* ne - integer not equal */
509 l = strlen (argv[op - 1]);
512 if (!isint (argv[op - 1], &l))
513 integer_expected_error (_("before -ne"));
516 r = strlen (argv[op + 2]);
519 if (!isint (argv[op + 1], &r))
520 integer_expected_error (_("after -ne"));
523 return (TRUE == (l != r));
528 if (argv[op][2] == 'q' && !argv[op][3])
530 /* eq - integer equal */
532 l = strlen (argv[op - 1]);
535 if (!isint (argv[op - 1], &l))
536 integer_expected_error (_("before -eq"));
539 r = strlen (argv[op + 2]);
542 if (!isint (argv[op + 1], &r))
543 integer_expected_error (_("after -eq"));
546 return (TRUE == (l == r));
549 if (argv[op][2] == 'f' && !argv[op][3])
551 /* ef - hard link? */
553 if (l_is_l || r_is_l)
554 test_syntax_error (_("-ef does not accept -l\n"), NULL);
555 if (stat (argv[op - 1], &stat_buf) < 0)
557 if (stat (argv[op + 1], &stat_spare) < 0)
560 (stat_buf.st_dev == stat_spare.st_dev &&
561 stat_buf.st_ino == stat_spare.st_ino));
566 if ('t' == argv[op][2] && '\000' == argv[op][3])
568 /* ot - older than */
572 if (l_is_l || r_is_l)
573 test_syntax_error (_("-ot does not accept -l\n"), NULL);
574 le = age_of (argv[op - 1], <);
575 re = age_of (argv[op + 1], &rt);
576 return le < re || (re == 0 && lt < rt);
581 /* FIXME: is this dead code? */
582 test_syntax_error (_("unknown binary operator\n"), argv[op]);
585 if (argv[op][0] == '=' && !argv[op][1])
587 value = (strcmp (argv[pos], argv[pos + 2]) == 0);
589 return (TRUE == value);
592 if (strcmp (argv[op], "!=") == 0)
594 value = (strcmp (argv[pos], argv[pos + 2]) != 0);
596 return (TRUE == value);
604 unary_operator (void)
607 struct stat stat_buf;
609 switch (argv[pos][1])
614 /* All of the following unary operators use unary_advance (), which
615 checks to make sure that there is an argument, and then advances
616 pos right past it. This means that pos - 1 is the location of the
619 case 'a': /* file exists in the file system? */
622 value = -1 != stat (argv[pos - 1], &stat_buf);
623 return (TRUE == value);
625 case 'r': /* file is readable? */
627 value = -1 != eaccess (argv[pos - 1], R_OK);
628 return (TRUE == value);
630 case 'w': /* File is writable? */
632 value = -1 != eaccess (argv[pos - 1], W_OK);
633 return (TRUE == value);
635 case 'x': /* File is executable? */
637 value = -1 != eaccess (argv[pos - 1], X_OK);
638 return (TRUE == value);
640 case 'O': /* File is owned by you? */
642 if (stat (argv[pos - 1], &stat_buf) < 0)
645 return (TRUE == (geteuid () == stat_buf.st_uid));
647 case 'G': /* File is owned by your group? */
649 if (stat (argv[pos - 1], &stat_buf) < 0)
652 return (TRUE == (getegid () == stat_buf.st_gid));
654 case 'f': /* File is a file? */
656 if (stat (argv[pos - 1], &stat_buf) < 0)
659 /* Under POSIX, -f is true if the given file exists
660 and is a regular file. */
661 return (TRUE == ((S_ISREG (stat_buf.st_mode)) ||
662 (0 == (stat_buf.st_mode & S_IFMT))));
664 case 'd': /* File is a directory? */
666 if (stat (argv[pos - 1], &stat_buf) < 0)
669 return (TRUE == (S_ISDIR (stat_buf.st_mode)));
671 case 's': /* File has something in it? */
673 if (stat (argv[pos - 1], &stat_buf) < 0)
676 return (TRUE == (stat_buf.st_size > (off_t) 0));
678 case 'S': /* File is a socket? */
679 #if !defined (S_ISSOCK)
684 if (stat (argv[pos - 1], &stat_buf) < 0)
687 return (TRUE == (S_ISSOCK (stat_buf.st_mode)));
688 #endif /* S_ISSOCK */
690 case 'c': /* File is character special? */
692 if (stat (argv[pos - 1], &stat_buf) < 0)
695 return (TRUE == (S_ISCHR (stat_buf.st_mode)));
697 case 'b': /* File is block special? */
699 if (stat (argv[pos - 1], &stat_buf) < 0)
702 return (TRUE == (S_ISBLK (stat_buf.st_mode)));
704 case 'p': /* File is a named pipe? */
709 if (stat (argv[pos - 1], &stat_buf) < 0)
711 return (TRUE == (S_ISFIFO (stat_buf.st_mode)));
712 #endif /* S_ISFIFO */
714 case 'L': /* Same as -h */
717 case 'h': /* File is a symbolic link? */
722 /* An empty filename is not a valid pathname. */
723 if ((argv[pos - 1][0] == '\0') ||
724 (lstat (argv[pos - 1], &stat_buf) < 0))
727 return (TRUE == (S_ISLNK (stat_buf.st_mode)));
730 case 'u': /* File is setuid? */
735 if (stat (argv[pos - 1], &stat_buf) < 0)
738 return (TRUE == (0 != (stat_buf.st_mode & S_ISUID)));
741 case 'g': /* File is setgid? */
746 if (stat (argv[pos - 1], &stat_buf) < 0)
749 return (TRUE == (0 != (stat_buf.st_mode & S_ISGID)));
752 case 'k': /* File has sticky bit set? */
754 if (stat (argv[pos - 1], &stat_buf) < 0)
757 /* This is not Posix, and is not defined on some Posix systems. */
760 return (TRUE == (0 != (stat_buf.st_mode & S_ISVTX)));
763 case 't': /* File (fd) is a terminal? */
767 if (!isint (argv[pos - 1], &fd))
768 integer_expected_error (_("after -t"));
769 return (TRUE == (fd == (int) fd && isatty (fd)));
772 case 'n': /* True if arg has some length. */
774 return (TRUE == (argv[pos - 1][0] != 0));
776 case 'z': /* True if arg has no length. */
778 return (TRUE == (argv[pos - 1][0] == '\0'));
793 while ((pos < argc) && strcmp (argv[pos], "-a") == 0)
796 value = TRUTH_AND (value, and ());
798 return (TRUE == value);
813 while ((pos < argc) && strcmp (argv[pos], "-o") == 0)
816 value = TRUTH_OR (value, or ());
819 return (TRUE == value);
832 return (FALSE ^ (or ())); /* Same with this. */
835 /* Return TRUE if S is one of the test command's binary operators. */
839 return ((STREQ (s, "=")) || (STREQ (s, "!=")) || (STREQ (s, "-nt")) ||
840 (STREQ (s, "-ot")) || (STREQ (s, "-ef")) || (STREQ (s, "-eq")) ||
841 (STREQ (s, "-ne")) || (STREQ (s, "-lt")) || (STREQ (s, "-le")) ||
842 (STREQ (s, "-gt")) || (STREQ (s, "-ge")));
845 /* Return nonzero if OP is one of the test command's unary operators. */
847 test_unop (char const *op)
854 case 'a': case 'b': case 'c': case 'd': case 'e':
855 case 'f': case 'g': case 'h': case 'k': case 'n':
856 case 'o': case 'p': case 'r': case 's': case 't':
857 case 'u': case 'w': case 'x': case 'z':
858 case 'G': case 'L': case 'O': case 'S': case 'N':
868 return argv[pos++][0] != '\0';
876 if (STREQ (argv[pos], "!"))
879 value = ! one_argument ();
881 else if (argv[pos][0] == '-'
882 && argv[pos][1] != '\0'
883 && argv[pos][2] == '\0')
885 if (test_unop (argv[pos]))
886 value = unary_operator ();
888 test_syntax_error (_("%s: unary operator expected\n"), argv[pos]);
896 three_arguments (void)
900 if (binop (argv[pos + 1]))
901 value = binary_operator (false);
902 else if (STREQ (argv[pos], "!"))
905 value = !two_arguments ();
907 else if (STREQ (argv[pos], "(") && STREQ (argv[pos + 2], ")"))
910 value = one_argument ();
913 else if (STREQ (argv[pos + 1], "-a") || STREQ (argv[pos + 1], "-o"))
916 test_syntax_error (_("%s: binary operator expected\n"), argv[pos+1]);
920 /* This is an implementation of a Posix.2 proposal by David Korn. */
922 posixtest (int nargs)
929 value = one_argument ();
933 value = two_arguments ();
937 value = three_arguments ();
941 if (STREQ (argv[pos], "!"))
944 value = !three_arguments ();
947 if (STREQ (argv[pos], "(") && STREQ (argv[pos + 3], ")"))
950 value = two_arguments ();
965 #if defined (TEST_STANDALONE)
966 # include "long-options.h"
972 fprintf (stderr, _("Try `%s --help' for more information.\n"),
977 Usage: test EXPRESSION\n\
978 or: [ EXPRESSION ]\n\
980 Exit with the status determined by EXPRESSION.\n\
983 fputs (HELP_OPTION_DESCRIPTION, stdout);
984 fputs (VERSION_OPTION_DESCRIPTION, stdout);
987 EXPRESSION is true or false and sets exit status. It is one of:\n\
991 ( EXPRESSION ) EXPRESSION is true\n\
992 ! EXPRESSION EXPRESSION is false\n\
993 EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true\n\
994 EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true\n\
998 [-n] STRING the length of STRING is nonzero\n\
999 -z STRING the length of STRING is zero\n\
1000 STRING1 = STRING2 the strings are equal\n\
1001 STRING1 != STRING2 the strings are not equal\n\
1005 INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2\n\
1006 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2\n\
1007 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2\n\
1008 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2\n\
1009 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2\n\
1010 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2\n\
1014 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers\n\
1015 FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2\n\
1016 FILE1 -ot FILE2 FILE1 is older than FILE2\n\
1020 -b FILE FILE exists and is block special\n\
1021 -c FILE FILE exists and is character special\n\
1022 -d FILE FILE exists and is a directory\n\
1023 -e FILE FILE exists\n\
1026 -f FILE FILE exists and is a regular file\n\
1027 -g FILE FILE exists and is set-group-ID\n\
1028 -h FILE FILE exists and is a symbolic link (same as -L)\n\
1029 -G FILE FILE exists and is owned by the effective group ID\n\
1030 -k FILE FILE exists and has its sticky bit set\n\
1033 -L FILE FILE exists and is a symbolic link (same as -h)\n\
1034 -O FILE FILE exists and is owned by the effective user ID\n\
1035 -p FILE FILE exists and is a named pipe\n\
1036 -r FILE FILE exists and is readable\n\
1037 -s FILE FILE exists and has a size greater than zero\n\
1040 -S FILE FILE exists and is a socket\n\
1041 -t [FD] file descriptor FD (stdout by default) is opened on a terminal\n\
1042 -u FILE FILE exists and its set-user-ID bit is set\n\
1043 -w FILE FILE exists and is writable\n\
1044 -x FILE FILE exists and is executable\n\
1048 Beware that parentheses need to be escaped (e.g., by backslashes) for shells.\n\
1049 INTEGER may also be -l STRING, which evaluates to the length of STRING.\n\
1051 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1055 #endif /* TEST_STANDALONE */
1057 #if !defined (TEST_STANDALONE)
1058 # define main test_command
1061 #define WRITTEN_BY _("Written by Kevin Braunsdorf and Matthew Bradburn.")
1070 main (int margc, char **margv)
1074 #if !defined (TEST_STANDALONE)
1077 code = setjmp (test_exit_buf);
1080 return (test_error_return);
1081 #else /* TEST_STANDALONE */
1082 initialize_main (&margc, &margv);
1083 program_name = margv[0];
1084 setlocale (LC_ALL, "");
1085 bindtextdomain (PACKAGE, LOCALEDIR);
1086 textdomain (PACKAGE);
1088 exit_failure = TEST_FAILURE;
1089 atexit (close_stdout);
1090 #endif /* TEST_STANDALONE */
1096 /* Recognize --help or --version, but only when invoked in the
1097 "[" form, and when the last argument is not "]". POSIX
1098 allows "[ --help" and "[ --version" to have the usual GNU
1099 behavior, but it requires "test --help" and "test --version"
1100 to exit silently with status 1. */
1101 if (margc < 2 || strcmp (margv[margc - 1], "]") != 0)
1103 parse_long_options (margc, margv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
1105 test_syntax_error (_("missing `]'\n"), NULL);
1115 test_exit (SHELL_BOOLEAN (FALSE));
1117 value = posixtest (argc - 1);
1120 test_syntax_error (_("too many arguments\n"), NULL);
1122 test_exit (SHELL_BOOLEAN (value));