env.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. * Note: env bypasses shell builtins, so don't xexec().
  8. *
  9. * Deviations from posix: "-" argument and -0
  10. USE_ENV(NEWTOY(env, "^i0u*", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_ARGFAIL(125)))
  11. config ENV
  12. bool "env"
  13. default y
  14. help
  15. usage: env [-i] [-u NAME] [NAME=VALUE...] [COMMAND...]
  16. Set the environment for command invocation, or list environment variables.
  17. -i Clear existing environment
  18. -u NAME Remove NAME from the environment
  19. -0 Use null instead of newline in output
  20. */
  21. #define FOR_env
  22. #include "toys.h"
  23. GLOBALS(
  24. struct arg_list *u;
  25. )
  26. void env_main(void)
  27. {
  28. char **ev = toys.optargs, **ee = 0, **set QUIET, *path = getenv("PATH");
  29. struct string_list *sl = 0;
  30. struct arg_list *u;
  31. // If first nonoption argument is "-" treat it as -i
  32. if (*ev && **ev == '-' && !(*ev)[1]) {
  33. toys.optflags |= FLAG_i;
  34. ev++;
  35. }
  36. if (FLAG(i)) ee = set = xzalloc(sizeof(void *)*(toys.optc+1));
  37. else for (u = TT.u; u; u = u->next) xunsetenv(u->arg);
  38. for (; *ev; ev++) {
  39. if (strchr(*ev, '=')) {
  40. if (FLAG(i)) *set++ = *ev;
  41. else xsetenv(xstrdup(*ev), 0);
  42. if (!strncmp(*ev, "PATH=", 5)) path=(*ev)+5;
  43. } else {
  44. // unfortunately, posix has no exec combining p and e, so do p ourselves
  45. if (!strchr(*ev, '/') && path) {
  46. errno = ENOENT;
  47. for (sl = find_in_path(path, *ev); sl; sl = sl->next)
  48. execve(sl->str, ev, ee ? : environ);
  49. } else execve(*ev, ev, ee ? : environ);
  50. perror_msg("exec %s", *ev);
  51. _exit(126+(errno == ENOENT));
  52. }
  53. }
  54. for (ev = ee ? : environ; *ev; ev++) xprintf("%s%c", *ev, '\n'*!FLAG(0));
  55. }