Patch-ID: bash32-032
[bash.git] / examples / loadables / basename.c
blob7f254c7679f59e23f763f12a8c96ba889f708fd1
1 /* basename - return nondirectory portion of pathname */
3 /* See Makefile for compilation details. */
5 #include "config.h"
7 #if defined (HAVE_UNISTD_H)
8 # include <unistd.h>
9 #endif
11 #include <stdio.h>
12 #include "builtins.h"
13 #include "shell.h"
15 basename_builtin (list)
16 WORD_LIST *list;
18 int slen, sufflen, off;
19 char *string, *suffix, *fn;
21 if (list == 0)
23 builtin_usage ();
24 return (EX_USAGE);
27 if (no_options (list))
28 return (EX_USAGE);
30 string = list->word->word;
31 suffix = (char *)NULL;
32 if (list->next)
34 list = list->next;
35 suffix = list->word->word;
38 if (list->next)
40 builtin_usage ();
41 return (EX_USAGE);
44 slen = strlen (string);
46 /* Strip trailing slashes */
47 while (slen > 0 && string[slen - 1] == '/')
48 slen--;
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)
55 fputs ("/\n", stdout);
56 return (EXECUTION_SUCCESS);
59 /* (3) If there are any trailing slash characters in string, they
60 shall be removed. */
61 string[slen] = '\0';
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;
70 fn = string + slen + 1;
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)
79 sufflen = strlen (suffix);
80 slen = strlen (fn);
81 if (sufflen < slen)
83 off = slen - sufflen;
84 if (strcmp (fn + off, suffix) == 0)
85 fn[off] = '\0';
88 printf ("%s\n", fn);
89 return (EXECUTION_SUCCESS);
92 char *basename_doc[] = {
93 "The STRING is converted to a filename corresponding to the last",
94 "pathname component in STRING. If the suffix string SUFFIX is",
95 "supplied, it is removed.",
96 (char *)NULL
99 /* The standard structure describing a builtin command. bash keeps an array
100 of these structures. */
101 struct builtin basename_struct = {
102 "basename", /* builtin name */
103 basename_builtin, /* function implementing the builtin */
104 BUILTIN_ENABLED, /* initial flags for builtin */
105 basename_doc, /* array of long documentation strings. */
106 "basename string [suffix]", /* usage synopsis */
107 0 /* reserved for internal use */