| 1 | /* basename - return nondirectory portion of pathname */
|
|---|
| 2 |
|
|---|
| 3 | /* See Makefile for compilation details. */
|
|---|
| 4 |
|
|---|
| 5 | #include "config.h"
|
|---|
| 6 |
|
|---|
| 7 | #if defined (HAVE_UNISTD_H)
|
|---|
| 8 | # include <unistd.h>
|
|---|
| 9 | #endif
|
|---|
| 10 |
|
|---|
| 11 | #include <stdio.h>
|
|---|
| 12 | #include "builtins.h"
|
|---|
| 13 | #include "shell.h"
|
|---|
| 14 |
|
|---|
| 15 | basename_builtin (list)
|
|---|
| 16 | WORD_LIST *list;
|
|---|
| 17 | {
|
|---|
| 18 | int slen, sufflen, off;
|
|---|
| 19 | char *string, *suffix, *fn;
|
|---|
| 20 |
|
|---|
| 21 | if (list == 0)
|
|---|
| 22 | {
|
|---|
| 23 | builtin_usage ();
|
|---|
| 24 | return (EX_USAGE);
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | if (no_options (list))
|
|---|
| 28 | return (EX_USAGE);
|
|---|
| 29 |
|
|---|
| 30 | string = list->word->word;
|
|---|
| 31 | suffix = (char *)NULL;
|
|---|
| 32 | if (list->next)
|
|---|
| 33 | {
|
|---|
| 34 | list = list->next;
|
|---|
| 35 | suffix = list->word->word;
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | if (list->next)
|
|---|
| 39 | {
|
|---|
| 40 | builtin_usage ();
|
|---|
| 41 | return (EX_USAGE);
|
|---|
| 42 | }
|
|---|
| 43 |
|
|---|
| 44 | slen = strlen (string);
|
|---|
| 45 |
|
|---|
| 46 | /* Strip trailing slashes */
|
|---|
| 47 | while (slen > 0 && string[slen - 1] == '/')
|
|---|
| 48 | slen--;
|
|---|
| 49 |
|
|---|
| 50 | /* (2) If string consists entirely of slash characters, string shall be
|
|---|
| 51 | set to a single slash character. In this case, skip steps (3)
|
|---|
| 52 | through (5). */
|
|---|
| 53 | if (slen == 0)
|
|---|
| 54 | {
|
|---|
| 55 | fputs ("/\n", stdout);
|
|---|
| 56 | return (EXECUTION_SUCCESS);
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|
| 59 | /* (3) If there are any trailing slash characters in string, they
|
|---|
| 60 | shall be removed. */
|
|---|
| 61 | string[slen] = '\0';
|
|---|
| 62 |
|
|---|
| 63 | /* (4) If there are any slash characters remaining in string, the prefix
|
|---|
| 64 | of string up to an including the last slash character in string
|
|---|
| 65 | shall be removed. */
|
|---|
| 66 | while (--slen >= 0)
|
|---|
| 67 | if (string[slen] == '/')
|
|---|
| 68 | break;
|
|---|
| 69 |
|
|---|
| 70 | fn = string + slen + 1;
|
|---|
| 71 |
|
|---|
| 72 | /* (5) If the suffix operand is present, is not identical to the
|
|---|
| 73 | characters remaining in string, and is identical to a suffix
|
|---|
| 74 | of the characters remaining in string, the suffix suffix
|
|---|
| 75 | shall be removed from string. Otherwise, string shall not be
|
|---|
| 76 | modified by this step. */
|
|---|
| 77 | if (suffix)
|
|---|
| 78 | {
|
|---|
| 79 | sufflen = strlen (suffix);
|
|---|
| 80 | slen = strlen (fn);
|
|---|
| 81 | if (sufflen < slen)
|
|---|
| 82 | {
|
|---|
| 83 | off = slen - sufflen;
|
|---|
| 84 | if (strcmp (fn + off, suffix) == 0)
|
|---|
|
|---|