• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
9 USE_ENV(NEWTOY(env, "^0iu*", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_ARGFAIL(125)))
10 
11 config ENV
12   bool "env"
13   default y
14   help
15     usage: env [-i] [-u NAME] [NAME=VALUE...] [COMMAND [ARG...]]
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 
27 GLOBALS(
28   struct arg_list *u;
29 );
30 
env_main(void)31 void env_main(void)
32 {
33   char **ev = toys.optargs;
34   struct arg_list *u;
35 
36   // If first nonoption argument is "-" treat it as -i
37   if (*ev && **ev == '-' && !(*ev)[1]) {
38     toys.optflags |= FLAG_i;
39     ev++;
40   }
41 
42   if (FLAG(i)) xclearenv();
43   else for (u = TT.u; u; u = u->next) xunsetenv(u->arg);
44 
45   for (; *ev; ev++)
46     if (strchr(*ev, '=')) xsetenv(xstrdup(*ev), 0);
47     else {
48       // a common use of env is to bypass shell builtins
49       toys.stacktop = 0;
50       xexec(ev);
51     }
52 
53   for (ev = environ; *ev; ev++) xprintf("%s%c", *ev, '\n'*!FLAG(0));
54 }
55