1 /* GNU test program (ksb and mjb) */
3 /* Modified to run with the GNU shell by bfox. */
5 /* Copyright (C) 1987-2016 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 <http://www.gnu.org/licenses/>. */
20 /* Define TEST_STANDALONE to get the /bin/test version. Otherwise, you get
21 the shell builtin version. */
23 /* Without this pragma, gcc 4.6.2 20111027 mistakenly suggests that
24 the advance function might be candidate for attribute 'pure'. */
25 #if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
26 # pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
31 #include <sys/types.h>
33 #define TEST_STANDALONE 1
39 /* The official name of this program (e.g., no 'g' prefix). */
41 # define PROGRAM_NAME "["
43 # define PROGRAM_NAME "test"
48 #include "stat-time.h"
49 #include "strnumcmp.h"
55 # include <sys/param.h>
58 /* Exit status for syntax errors, etc. */
59 enum { TEST_TRUE
, TEST_FALSE
, TEST_FAILURE
};
61 #if defined TEST_STANDALONE
62 # define test_exit(val) exit (val)
63 # define test_main_return(val) return val
65 static jmp_buf test_exit_buf
;
66 static int test_error_return
= 0;
67 # define test_exit(val) test_error_return = val, longjmp (test_exit_buf, 1)
68 # define test_main_return(val) test_exit (val)
69 #endif /* !TEST_STANDALONE */
71 static int pos
; /* The offset of the current argument in ARGV. */
72 static int argc
; /* The number of arguments present in ARGV. */
73 static char **argv
; /* The argument list. */
75 static bool test_unop (char const *s
);
76 static bool unary_operator (void);
77 static bool binary_operator (bool);
78 static bool two_arguments (void);
79 static bool three_arguments (void);
80 static bool posixtest (int);
82 static bool expr (void);
83 static bool term (void);
84 static bool and (void);
85 static bool or (void);
87 static void test_syntax_error (char const *format
, ...)
89 static void beyond (void) ATTRIBUTE_NORETURN
;
92 test_syntax_error (char const *format
, ...)
95 va_start (ap
, format
);
96 verror (0, 0, format
, ap
);
97 test_exit (TEST_FAILURE
);
100 /* Increment our position in the argument list. Check that we're not
101 past the end of the argument list. This check is suppressed if the
102 argument is false. */
109 if (f
&& pos
>= argc
)
121 * beyond - call when we're beyond the end of the argument list (an
127 test_syntax_error (_("missing argument after %s"), quote (argv
[argc
- 1]));
130 /* If the characters pointed to by STRING constitute a valid number,
131 return a pointer to the start of the number, skipping any blanks or
132 leading '+'. Otherwise, report an error and exit. */
134 find_int (char const *string
)
137 char const *number_start
;
139 for (p
= string
; isblank (to_uchar (*p
)); p
++)
157 while (isblank (to_uchar (*p
)))
163 test_syntax_error (_("invalid integer %s"), quote (string
));
166 /* Find the modification time of FILE, and stuff it into *MTIME.
167 Return true if successful. */
169 get_mtime (char const *filename
, struct timespec
*mtime
)
172 bool ok
= (stat (filename
, &finfo
) == 0);
174 static struct timespec
const zero
;
178 *mtime
= get_stat_mtime (&finfo
);
182 /* Return true if S is one of the test command's binary operators. */
184 binop (char const *s
)
186 return ((STREQ (s
, "=")) || (STREQ (s
, "!=")) || (STREQ (s
, "==")) ||
187 (STREQ (s
, "-nt")) ||
188 (STREQ (s
, "-ot")) || (STREQ (s
, "-ef")) || (STREQ (s
, "-eq")) ||
189 (STREQ (s
, "-ne")) || (STREQ (s
, "-lt")) || (STREQ (s
, "-le")) ||
190 (STREQ (s
, "-gt")) || (STREQ (s
, "-ge")));
194 * term - parse a term and return 1 or 0 depending on whether the term
195 * evaluates to true or false, respectively.
198 * '-'('h'|'d'|'f'|'r'|'s'|'w'|'c'|'b'|'p'|'u'|'g'|'k') filename
199 * '-'('L'|'x') filename
201 * '-'('z'|'n') string
203 * string ('!='|'=') string
204 * <int> '-'(eq|ne|le|lt|ge|gt) <int>
205 * file '-'(nt|ot|ef) file
209 * positive and negative integers
215 bool negated
= false;
217 /* Deal with leading 'not's. */
218 while (pos
< argc
&& argv
[pos
][0] == '!' && argv
[pos
][1] == '\0')
227 /* A paren-bracketed argument. */
228 if (argv
[pos
][0] == '(' && argv
[pos
][1] == '\0')
235 pos
+ nargs
< argc
&& ! STREQ (argv
[pos
+ nargs
], ")");
243 value
= posixtest (nargs
);
245 test_syntax_error (_("%s expected"), quote (")"));
247 if (argv
[pos
][0] != ')' || argv
[pos
][1])
248 test_syntax_error (_("%s expected, found %s"),
249 quote_n (0, ")"), quote_n (1, argv
[pos
]));
253 /* Are there enough arguments left that this could be dyadic? */
254 else if (4 <= argc
- pos
&& STREQ (argv
[pos
], "-l") && binop (argv
[pos
+ 2]))
255 value
= binary_operator (true);
256 else if (3 <= argc
- pos
&& binop (argv
[pos
+ 1]))
257 value
= binary_operator (false);
259 /* It might be a switch type argument. */
260 else if (argv
[pos
][0] == '-' && argv
[pos
][1] && argv
[pos
][2] == '\0')
262 if (test_unop (argv
[pos
]))
263 value
= unary_operator ();
265 test_syntax_error (_("%s: unary operator expected"), quote (argv
[pos
]));
269 value
= (argv
[pos
][0] != '\0');
273 return negated
^ value
;
277 binary_operator (bool l_is_l
)
280 struct stat stat_buf
, stat_spare
;
281 /* Is the right integer expression of the form '-l string'? */
288 if ((op
< argc
- 2) && STREQ (argv
[op
+ 1], "-l"))
296 if (argv
[op
][0] == '-')
298 /* check for eq, nt, and stuff */
299 if ((((argv
[op
][1] == 'l' || argv
[op
][1] == 'g')
300 && (argv
[op
][2] == 'e' || argv
[op
][2] == 't'))
301 || (argv
[op
][1] == 'e' && argv
[op
][2] == 'q')
302 || (argv
[op
][1] == 'n' && argv
[op
][2] == 'e'))
305 char lbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
306 char rbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
307 char const *l
= (l_is_l
308 ? umaxtostr (strlen (argv
[op
- 1]), lbuf
)
309 : find_int (argv
[op
- 1]));
310 char const *r
= (r_is_l
311 ? umaxtostr (strlen (argv
[op
+ 2]), rbuf
)
312 : find_int (argv
[op
+ 1]));
313 int cmp
= strintcmp (l
, r
);
314 bool xe_operator
= (argv
[op
][2] == 'e');
316 return (argv
[op
][1] == 'l' ? cmp
< xe_operator
317 : argv
[op
][1] == 'g' ? cmp
> - xe_operator
318 : (cmp
!= 0) == xe_operator
);
327 if (argv
[op
][2] == 't' && !argv
[op
][3])
329 /* nt - newer than */
330 struct timespec lt
, rt
;
333 if (l_is_l
|| r_is_l
)
334 test_syntax_error (_("-nt does not accept -l"), NULL
);
335 le
= get_mtime (argv
[op
- 1], <
);
336 re
= get_mtime (argv
[op
+ 1], &rt
);
337 return le
&& (!re
|| timespec_cmp (lt
, rt
) > 0);
342 if (argv
[op
][2] == 'f' && !argv
[op
][3])
344 /* ef - hard link? */
346 if (l_is_l
|| r_is_l
)
347 test_syntax_error (_("-ef does not accept -l"), NULL
);
348 return (stat (argv
[op
- 1], &stat_buf
) == 0
349 && stat (argv
[op
+ 1], &stat_spare
) == 0
350 && stat_buf
.st_dev
== stat_spare
.st_dev
351 && stat_buf
.st_ino
== stat_spare
.st_ino
);
356 if ('t' == argv
[op
][2] && '\000' == argv
[op
][3])
358 /* ot - older than */
359 struct timespec lt
, rt
;
362 if (l_is_l
|| r_is_l
)
363 test_syntax_error (_("-ot does not accept -l"), NULL
);
364 le
= get_mtime (argv
[op
- 1], <
);
365 re
= get_mtime (argv
[op
+ 1], &rt
);
366 return re
&& (!le
|| timespec_cmp (lt
, rt
) < 0);
371 /* FIXME: is this dead code? */
372 test_syntax_error (_("%s: unknown binary operator"), quote (argv
[op
]));
375 if (argv
[op
][0] == '='
376 && (!argv
[op
][1] || ((argv
[op
][1] == '=') && !argv
[op
][2])))
378 bool value
= STREQ (argv
[pos
], argv
[pos
+ 2]);
383 if (STREQ (argv
[op
], "!="))
385 bool value
= !STREQ (argv
[pos
], argv
[pos
+ 2]);
395 unary_operator (void)
397 struct stat stat_buf
;
399 switch (argv
[pos
][1])
404 /* All of the following unary operators use unary_advance (), which
405 checks to make sure that there is an argument, and then advances
406 pos right past it. This means that pos - 1 is the location of the
409 case 'a': /* file exists in the file system? */
412 return stat (argv
[pos
- 1], &stat_buf
) == 0;
414 case 'r': /* file is readable? */
416 return euidaccess (argv
[pos
- 1], R_OK
) == 0;
418 case 'w': /* File is writable? */
420 return euidaccess (argv
[pos
- 1], W_OK
) == 0;
422 case 'x': /* File is executable? */
424 return euidaccess (argv
[pos
- 1], X_OK
) == 0;
426 case 'O': /* File is owned by you? */
429 if (stat (argv
[pos
- 1], &stat_buf
) != 0)
432 uid_t euid
= geteuid ();
434 return ! (euid
== NO_UID
&& errno
) && euid
== stat_buf
.st_uid
;
437 case 'G': /* File is owned by your group? */
440 if (stat (argv
[pos
- 1], &stat_buf
) != 0)
443 gid_t egid
= getegid ();
445 return ! (egid
== NO_GID
&& errno
) && egid
== stat_buf
.st_gid
;
448 case 'f': /* File is a file? */
450 /* Under POSIX, -f is true if the given file exists
451 and is a regular file. */
452 return (stat (argv
[pos
- 1], &stat_buf
) == 0
453 && S_ISREG (stat_buf
.st_mode
));
455 case 'd': /* File is a directory? */
457 return (stat (argv
[pos
- 1], &stat_buf
) == 0
458 && S_ISDIR (stat_buf
.st_mode
));
460 case 's': /* File has something in it? */
462 return (stat (argv
[pos
- 1], &stat_buf
) == 0
463 && 0 < stat_buf
.st_size
);
465 case 'S': /* File is a socket? */
467 return (stat (argv
[pos
- 1], &stat_buf
) == 0
468 && S_ISSOCK (stat_buf
.st_mode
));
470 case 'c': /* File is character special? */
472 return (stat (argv
[pos
- 1], &stat_buf
) == 0
473 && S_ISCHR (stat_buf
.st_mode
));
475 case 'b': /* File is block special? */
477 return (stat (argv
[pos
- 1], &stat_buf
) == 0
478 && S_ISBLK (stat_buf
.st_mode
));
480 case 'p': /* File is a named pipe? */
482 return (stat (argv
[pos
- 1], &stat_buf
) == 0
483 && S_ISFIFO (stat_buf
.st_mode
));
485 case 'L': /* Same as -h */
488 case 'h': /* File is a symbolic link? */
490 return (lstat (argv
[pos
- 1], &stat_buf
) == 0
491 && S_ISLNK (stat_buf
.st_mode
));
493 case 'u': /* File is setuid? */
495 return (stat (argv
[pos
- 1], &stat_buf
) == 0
496 && (stat_buf
.st_mode
& S_ISUID
));
498 case 'g': /* File is setgid? */
500 return (stat (argv
[pos
- 1], &stat_buf
) == 0
501 && (stat_buf
.st_mode
& S_ISGID
));
503 case 'k': /* File has sticky bit set? */
505 return (stat (argv
[pos
- 1], &stat_buf
) == 0
506 && (stat_buf
.st_mode
& S_ISVTX
));
508 case 't': /* File (fd) is a terminal? */
513 arg
= find_int (argv
[pos
- 1]);
515 fd
= strtol (arg
, NULL
, 10);
516 return (errno
!= ERANGE
&& 0 <= fd
&& fd
<= INT_MAX
&& isatty (fd
));
519 case 'n': /* True if arg has some length. */
521 return argv
[pos
- 1][0] != 0;
523 case 'z': /* True if arg has no length. */
525 return argv
[pos
- 1][0] == '\0';
542 if (! (pos
< argc
&& STREQ (argv
[pos
], "-a")))
561 if (! (pos
< argc
&& STREQ (argv
[pos
], "-o")))
577 return or (); /* Same with this. */
580 /* Return true if OP is one of the test command's unary operators. */
582 test_unop (char const *op
)
589 case 'a': case 'b': case 'c': case 'd': case 'e':
590 case 'f': case 'g': case 'h': case 'k': case 'n':
591 case 'o': case 'p': case 'r': case 's': case 't':
592 case 'u': case 'w': case 'x': case 'z':
593 case 'G': case 'L': case 'O': case 'S': case 'N':
603 return argv
[pos
++][0] != '\0';
611 if (STREQ (argv
[pos
], "!"))
614 value
= ! one_argument ();
616 else if (argv
[pos
][0] == '-'
617 && argv
[pos
][1] != '\0'
618 && argv
[pos
][2] == '\0')
620 if (test_unop (argv
[pos
]))
621 value
= unary_operator ();
623 test_syntax_error (_("%s: unary operator expected"), quote (argv
[pos
]));
631 three_arguments (void)
635 if (binop (argv
[pos
+ 1]))
636 value
= binary_operator (false);
637 else if (STREQ (argv
[pos
], "!"))
640 value
= !two_arguments ();
642 else if (STREQ (argv
[pos
], "(") && STREQ (argv
[pos
+ 2], ")"))
645 value
= one_argument ();
648 else if (STREQ (argv
[pos
+ 1], "-a") || STREQ (argv
[pos
+ 1], "-o"))
651 test_syntax_error (_("%s: binary operator expected"), quote (argv
[pos
+1]));
655 /* This is an implementation of a Posix.2 proposal by David Korn. */
657 posixtest (int nargs
)
664 value
= one_argument ();
668 value
= two_arguments ();
672 value
= three_arguments ();
676 if (STREQ (argv
[pos
], "!"))
679 value
= !three_arguments ();
682 if (STREQ (argv
[pos
], "(") && STREQ (argv
[pos
+ 3], ")"))
685 value
= two_arguments ();
700 #if defined TEST_STANDALONE
705 if (status
!= EXIT_SUCCESS
)
710 Usage: test EXPRESSION\n\
712 or: [ EXPRESSION ]\n\
717 Exit with the status determined by EXPRESSION.\n\
720 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
721 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
724 An omitted EXPRESSION defaults to false. Otherwise,\n\
725 EXPRESSION is true or false and sets exit status. It is one of:\n\
729 ( EXPRESSION ) EXPRESSION is true\n\
730 ! EXPRESSION EXPRESSION is false\n\
731 EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true\n\
732 EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true\n\
736 -n STRING the length of STRING is nonzero\n\
737 STRING equivalent to -n STRING\n\
738 -z STRING the length of STRING is zero\n\
739 STRING1 = STRING2 the strings are equal\n\
740 STRING1 != STRING2 the strings are not equal\n\
744 INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2\n\
745 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2\n\
746 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2\n\
747 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2\n\
748 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2\n\
749 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2\n\
753 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers\n\
754 FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2\n\
755 FILE1 -ot FILE2 FILE1 is older than FILE2\n\
759 -b FILE FILE exists and is block special\n\
760 -c FILE FILE exists and is character special\n\
761 -d FILE FILE exists and is a directory\n\
762 -e FILE FILE exists\n\
765 -f FILE FILE exists and is a regular file\n\
766 -g FILE FILE exists and is set-group-ID\n\
767 -G FILE FILE exists and is owned by the effective group ID\n\
768 -h FILE FILE exists and is a symbolic link (same as -L)\n\
769 -k FILE FILE exists and has its sticky bit set\n\
772 -L FILE FILE exists and is a symbolic link (same as -h)\n\
773 -O FILE FILE exists and is owned by the effective user ID\n\
774 -p FILE FILE exists and is a named pipe\n\
775 -r FILE FILE exists and read permission is granted\n\
776 -s FILE FILE exists and has a size greater than zero\n\
779 -S FILE FILE exists and is a socket\n\
780 -t FD file descriptor FD is opened on a terminal\n\
781 -u FILE FILE exists and its set-user-ID bit is set\n\
782 -w FILE FILE exists and write permission is granted\n\
783 -x FILE FILE exists and execute (or search) permission is granted\n\
787 Except for -h and -L, all FILE-related tests dereference symbolic links.\n\
788 Beware that parentheses need to be escaped (e.g., by backslashes) for shells.\n\
789 INTEGER may also be -l STRING, which evaluates to the length of STRING.\n\
793 NOTE: [ honors the --help and --version options, but test does not.\n\
794 test treats each of those as it treats any other nonempty STRING.\n\
796 printf (USAGE_BUILTIN_WARNING
, _("test and/or ["));
797 emit_ancillary_info (PROGRAM_NAME
);
801 #endif /* TEST_STANDALONE */
803 #if !defined TEST_STANDALONE
804 # define main test_command
808 proper_name ("Kevin Braunsdorf"), \
809 proper_name ("Matthew Bradburn")
818 main (int margc
, char **margv
)
822 #if !defined TEST_STANDALONE
825 code
= setjmp (test_exit_buf
);
828 return (test_error_return
);
829 #else /* TEST_STANDALONE */
830 initialize_main (&margc
, &margv
);
831 set_program_name (margv
[0]);
832 setlocale (LC_ALL
, "");
833 bindtextdomain (PACKAGE
, LOCALEDIR
);
834 textdomain (PACKAGE
);
836 initialize_exit_failure (TEST_FAILURE
);
837 atexit (close_stdout
);
838 #endif /* TEST_STANDALONE */
844 /* Recognize --help or --version, but only when invoked in the
845 "[" form, when the last argument is not "]". Use direct
846 parsing, rather than parse_long_options, to avoid accepting
847 abbreviations. POSIX allows "[ --help" and "[ --version" to
848 have the usual GNU behavior, but it requires "test --help"
849 and "test --version" to exit silently with status 0. */
852 if (STREQ (margv
[1], "--help"))
853 usage (EXIT_SUCCESS
);
855 if (STREQ (margv
[1], "--version"))
857 version_etc (stdout
, PROGRAM_NAME
, PACKAGE_NAME
, Version
, AUTHORS
,
859 test_main_return (EXIT_SUCCESS
);
862 if (margc
< 2 || !STREQ (margv
[margc
- 1], "]"))
863 test_syntax_error (_("missing %s"), quote ("]"));
872 test_main_return (TEST_FALSE
);
874 value
= posixtest (argc
- 1);
877 test_syntax_error (_("extra argument %s"), quote (argv
[pos
]));
879 test_main_return (value
? TEST_TRUE
: TEST_FALSE
);