toybox/toys/posix/env.c
<<
>>
Prefs
   1/* env.c - Set the environment for command invocation.
   2 *
   3 * Copyright 2012 Tryn Mirell <tryn@mirell.org>
   4 *
   5 * http://opengroup.org/onlinepubs/9699919799/utilities/env.html
   6 *
   7 * Deviations from posix: "-" argument and -0
   8
   9USE_ENV(NEWTOY(env, "^0iu*", TOYFLAG_USR|TOYFLAG_BIN))
  10
  11config ENV
  12  bool "env"
  13  default y
  14  help
  15    usage: env [-i] [-u NAME] [NAME=VALUE...] [command [option...]]
  16
  17    Set the environment for command invocation, or list environment variables.
  18
  19    -i  Clear existing environment
  20    -u NAME     Remove NAME from the environment
  21    -0  Use null instead of newline in output
  22*/
  23
  24#define FOR_env
  25#include "toys.h"
  26
  27GLOBALS(
  28  struct arg_list *u;
  29);
  30
  31extern char **environ;
  32
  33void env_main(void)
  34{
  35  char **ev = toys.optargs;
  36
  37  // If first nonoption argument is "-" treat it as -i
  38  if (*ev && **ev == '-' && !(*ev)[1]) {
  39    toys.optflags |= FLAG_i;
  40    ev++;
  41  }
  42
  43  if (toys.optflags & FLAG_i) clearenv();
  44  while (TT.u) {
  45    unsetenv(TT.u->arg);
  46    TT.u = TT.u->next;
  47  }
  48
  49  for (; *ev; ev++) {
  50    char *name = *ev, *val = strchr(name, '=');
  51
  52    if (val) {
  53      *(val++) = 0;
  54      setenv(name, val, 1);
  55    } else xexec(ev);
  56  }
  57
  58  if (environ) for (ev = environ; *ev; ev++)
  59    xprintf("%s%c", *ev, '\n'*!(toys.optflags&FLAG_0));
  60}
  61