10f66f451Sopenharmony_ci/* env.c - Set the environment for command invocation.
20f66f451Sopenharmony_ci *
30f66f451Sopenharmony_ci * Copyright 2012 Tryn Mirell <tryn@mirell.org>
40f66f451Sopenharmony_ci *
50f66f451Sopenharmony_ci * http://opengroup.org/onlinepubs/9699919799/utilities/env.html
60f66f451Sopenharmony_ci *
70f66f451Sopenharmony_ci * Deviations from posix: "-" argument and -0
80f66f451Sopenharmony_ci
90f66f451Sopenharmony_ciUSE_ENV(NEWTOY(env, "^0iu*", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_ARGFAIL(125)))
100f66f451Sopenharmony_ci
110f66f451Sopenharmony_ciconfig ENV
120f66f451Sopenharmony_ci  bool "env"
130f66f451Sopenharmony_ci  default y
140f66f451Sopenharmony_ci  help
150f66f451Sopenharmony_ci    usage: env [-i] [-u NAME] [NAME=VALUE...] [COMMAND [ARG...]]
160f66f451Sopenharmony_ci
170f66f451Sopenharmony_ci    Set the environment for command invocation, or list environment variables.
180f66f451Sopenharmony_ci
190f66f451Sopenharmony_ci    -i	Clear existing environment
200f66f451Sopenharmony_ci    -u NAME	Remove NAME from the environment
210f66f451Sopenharmony_ci    -0	Use null instead of newline in output
220f66f451Sopenharmony_ci*/
230f66f451Sopenharmony_ci
240f66f451Sopenharmony_ci#define FOR_env
250f66f451Sopenharmony_ci#include "toys.h"
260f66f451Sopenharmony_ci
270f66f451Sopenharmony_ciGLOBALS(
280f66f451Sopenharmony_ci  struct arg_list *u;
290f66f451Sopenharmony_ci);
300f66f451Sopenharmony_ci
310f66f451Sopenharmony_civoid env_main(void)
320f66f451Sopenharmony_ci{
330f66f451Sopenharmony_ci  char **ev = toys.optargs;
340f66f451Sopenharmony_ci  struct arg_list *u;
350f66f451Sopenharmony_ci
360f66f451Sopenharmony_ci  // If first nonoption argument is "-" treat it as -i
370f66f451Sopenharmony_ci  if (*ev && **ev == '-' && !(*ev)[1]) {
380f66f451Sopenharmony_ci    toys.optflags |= FLAG_i;
390f66f451Sopenharmony_ci    ev++;
400f66f451Sopenharmony_ci  }
410f66f451Sopenharmony_ci
420f66f451Sopenharmony_ci  if (FLAG(i)) xclearenv();
430f66f451Sopenharmony_ci  else for (u = TT.u; u; u = u->next) xunsetenv(u->arg);
440f66f451Sopenharmony_ci
450f66f451Sopenharmony_ci  for (; *ev; ev++)
460f66f451Sopenharmony_ci    if (strchr(*ev, '=')) xsetenv(xstrdup(*ev), 0);
470f66f451Sopenharmony_ci    else {
480f66f451Sopenharmony_ci      // a common use of env is to bypass shell builtins
490f66f451Sopenharmony_ci      toys.stacktop = 0;
500f66f451Sopenharmony_ci      xexec(ev);
510f66f451Sopenharmony_ci    }
520f66f451Sopenharmony_ci
530f66f451Sopenharmony_ci  for (ev = environ; *ev; ev++) xprintf("%s%c", *ev, '\n'*!FLAG(0));
540f66f451Sopenharmony_ci}
55