aboutsummaryrefslogtreecommitdiff
path: root/toys
diff options
context:
space:
mode:
authorTryn Mirell <tryn@mirell.org>2012-01-15 23:20:06 -0600
committerTryn Mirell <tryn@mirell.org>2012-01-15 23:20:06 -0600
commitde584eb24173d6b708170ee1900fcec47091365e (patch)
tree4908b4e89359c7356155f784efa3e80c6abd7f39 /toys
parent66a69d9f5751fb38ebd2ade662b90b68a1cc7c2d (diff)
downloadtoybox-de584eb24173d6b708170ee1900fcec47091365e.tar.gz
Initial 'basename' implementation
Diffstat (limited to 'toys')
-rw-r--r--toys/basename.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/toys/basename.c b/toys/basename.c
new file mode 100644
index 00000000..33307327
--- /dev/null
+++ b/toys/basename.c
@@ -0,0 +1,53 @@
+/* vi: set sw=4 ts=4:
+ *
+ * basename.c
+
+USE_BASENAME(NEWTOY(basename, NULL, TOYFLAG_USR|TOYFLAG_BIN))
+
+config BASENAME
+ bool "basename"
+ default n
+ help
+ usage: basename string [suffix]
+ Return non-directory portion of a pathname
+*/
+
+#include "toys.h"
+
+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;
+ }
+
+ // remove trailing slash
+ if (arg[arglen - 1] == '/') {
+ arg[arglen - 1] = 0;
+ }
+
+ // get everything past the last /
+ base = strrchr(arg, '/') + 1;
+
+ // 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;
+ }
+
+ puts(base);
+}