aboutsummaryrefslogtreecommitdiff
path: root/toys/basename.c
diff options
context:
space:
mode:
authorTryn Mirell <tryn@mirell.org>2012-01-20 00:02:37 -0600
committerTryn Mirell <tryn@mirell.org>2012-01-20 00:02:37 -0600
commitffdfdc2fbd552d8bd1ba8a6696a5a4febd4945d6 (patch)
treeeed5c55ff12b427490c2070655fa46a594087dcb /toys/basename.c
parentacf4b10aa8d0f944cd8cbbc28b8912472af95003 (diff)
downloadtoybox-ffdfdc2fbd552d8bd1ba8a6696a5a4febd4945d6.tar.gz
'env' and 'basename' refactored
Diffstat (limited to 'toys/basename.c')
-rw-r--r--toys/basename.c41
1 files changed, 12 insertions, 29 deletions
diff --git a/toys/basename.c b/toys/basename.c
index b5ace421..8ac7e8c7 100644
--- a/toys/basename.c
+++ b/toys/basename.c
@@ -7,7 +7,7 @@
* See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html
-USE_BASENAME(NEWTOY(basename, NULL, TOYFLAG_USR|TOYFLAG_BIN))
+USE_BASENAME(NEWTOY(basename, "<1>2", TOYFLAG_USR|TOYFLAG_BIN))
config BASENAME
bool "basename"
@@ -22,40 +22,23 @@ config BASENAME
void basename_main(void)
{
- char *arg, *suffix, *base;
- int arglen;
-
- arg = toys.optargs[0];
- suffix = toys.optargs[1];
-
- // return null string if nothing provided
- if (!arg) return;
-
- arglen = strlen(arg);
-
- // handle the case where we only have single slash
- if (arglen == 1 && arg[0] == '/') {
- puts("/");
- return;
+ char *arg = toys.optargs[0], *suffix = toys.optargs[1], *base;
+
+ while ((base = strrchr(arg, '/'))) {
+ if (base == arg) break;
+ if (!base[1]) *base = 0;
+ else {
+ base++;
+ break;
+ }
}
- // remove trailing slash
- if (arg[arglen - 1] == '/') {
- arg[arglen - 1] = 0;
- }
-
- // get everything past the last /
- base = strrchr(arg, '/');
-
if (!base) base = arg;
- else base++;
-
- // handle the case where we have all slashes
- if (base[0] == 0) base = "/";
// chop off the suffix if provided
if (suffix) {
- strstr(base, suffix)[0] = 0;
+ char *s = strstr(base, suffix);
+ if (s && s != base) *s = 0;
}
puts(base);