Added gitignore entries needed to ignore derived objects generated from full build...
[bash.git] / examples / loadables / basename.c
blobb5705cb42766f9951f0c6baef01d424a4099cf0b
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"
14 #include "common.h"
16 basename_builtin (list)
17 WORD_LIST *list;
19 int slen, sufflen, off;
20 char *string, *suffix, *fn;
22 if (list == 0)
24 builtin_usage ();
25 return (EX_USAGE);
28 if (no_options (list))
29 return (EX_USAGE);
31 string = list->word->word;
32 suffix = (char *)NULL;
33 if (list->next)
35 list = list->next;
36 suffix = list->word->word;
39 if (list->next)
41 builtin_usage ();
42 return (EX_USAGE);
45 slen = strlen (string);
47 /* Strip trailing slashes */
48 while (slen > 0 && string[slen - 1] == '/')
49 slen--;
51 /* (2) If string consists entirely of slash characters, string shall be
52 set to a single slash character. In this case, skip steps (3)
53 through (5). */
54 if (slen == 0)
56 fputs ("/\n", stdout);
57 return (EXECUTION_SUCCESS);
60 /* (3) If there are any trailing slash characters in string, they
61 shall be removed. */
62 string[slen] = '\0';
64 /* (4) If there are any slash characters remaining in string, the prefix
65 of string up to an including the last slash character in string
66 shall be removed. */
67 while (--slen >= 0)
68 if (string[slen] == '/')
69 break;
71 fn = string + slen + 1;
73 /* (5) If the suffix operand is present, is not identical to the
74 characters remaining in string, and is identical to a suffix
75 of the characters remaining in string, the suffix suffix
76 shall be removed from string. Otherwise, string shall not be
77 modified by this step. */
78 if (suffix)
80 sufflen = strlen (suffix);
81 slen = strlen (fn);
82 if (sufflen < slen)
84 off = slen - sufflen;
85 if (strcmp (fn + off, suffix) == 0)
86 fn[off] = '\0';
89 printf ("%s\n", fn);
90 return (EXECUTION_SUCCESS);
93 char *basename_doc[] = {
94 "Return non-directory portion of pathname.",
95 "",
96 "The STRING is converted to a filename corresponding to the last",
97 "pathname component in STRING. If the suffix string SUFFIX is",
98 "supplied, it is removed.",
99 (char *)NULL
102 /* The standard structure describing a builtin command. bash keeps an array
103 of these structures. */
104 struct builtin basename_struct = {
105 "basename", /* builtin name */
106 basename_builtin, /* function implementing the builtin */
107 BUILTIN_ENABLED, /* initial flags for builtin */
108 basename_doc, /* array of long documentation strings. */
109 "basename string [suffix]", /* usage synopsis */
110 0 /* reserved for internal use */