toybox/toys/posix/basename.c
<<
>>
Prefs
   1/* basename.c - Return non-directory portion of a pathname
   2 *
   3 * Copyright 2012 Tryn Mirell <tryn@mirell.org>
   4 *
   5 * See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html
   6
   7
   8USE_BASENAME(NEWTOY(basename, "^<1as:", TOYFLAG_USR|TOYFLAG_BIN))
   9
  10config BASENAME
  11  bool "basename"
  12  default y
  13  help
  14    usage: basename [-a] [-s SUFFIX] NAME... | NAME [SUFFIX]
  15
  16    Return non-directory portion of a pathname removing suffix.
  17
  18    -a          All arguments are names
  19    -s SUFFIX   Remove suffix (implies -a)
  20*/
  21
  22#define FOR_basename
  23#include "toys.h"
  24
  25GLOBALS(
  26  char *s;
  27)
  28
  29void basename_main(void)
  30{
  31  char **arg;
  32
  33  if (toys.optflags&FLAG_s) toys.optflags |= FLAG_a;
  34
  35  if (!(toys.optflags&FLAG_a)) {
  36    if (toys.optc > 2) error_exit("too many args");
  37    TT.s = toys.optargs[1];
  38    toys.optargs[1] = NULL;
  39  }
  40
  41  for (arg = toys.optargs; *arg; ++arg) {
  42    char *base = basename(*arg), *p;
  43
  44    // Chop off the suffix if provided.
  45    if (TT.s && *TT.s && (p = strend(base, TT.s))) *p = 0;
  46    puts(base);
  47  }
  48}
  49