1 | /* env 1.1 - Set environment for command Author: Kees J. Bot
|
---|
2 | * 17 Dec 1997
|
---|
3 | */
|
---|
4 | #define nil 0
|
---|
5 | #include <sys/types.h>
|
---|
6 | #include <stdio.h>
|
---|
7 | #include <stdlib.h>
|
---|
8 | #include <string.h>
|
---|
9 | #include <unistd.h>
|
---|
10 | #include <errno.h>
|
---|
11 |
|
---|
12 | int main(int argc, char **argv)
|
---|
13 | {
|
---|
14 | int i;
|
---|
15 | int iflag= 0;
|
---|
16 | int aflag= 0;
|
---|
17 | extern char **environ;
|
---|
18 |
|
---|
19 | i= 1;
|
---|
20 | while (i < argc && argv[i][0] == '-') {
|
---|
21 | char *opt= argv[i++] + 1;
|
---|
22 |
|
---|
23 | if (opt[0] == '-' && opt[1] == 0) break; /* -- */
|
---|
24 |
|
---|
25 | if (opt[0] == 0) iflag= 1; /* - */
|
---|
26 |
|
---|
27 | while (*opt != 0) switch (*opt++) {
|
---|
28 | case 'i':
|
---|
29 | iflag= 1; /* Clear environment. */
|
---|
30 | break;
|
---|
31 | case 'a': /* Specify arg 0 separately. */
|
---|
32 | aflag= 1;
|
---|
33 | break;
|
---|
34 | default:
|
---|
35 | fprintf(stderr,
|
---|
36 | "Usage: env [-ia] [name=value] ... [utility [argument ...]]\n");
|
---|
37 | exit(1);
|
---|
38 | }
|
---|
39 | }
|
---|
40 |
|
---|
41 | /* Clear the environment if -i. */
|
---|
42 | if (iflag) *environ= nil;
|
---|
43 |
|
---|
44 | /* Set the new environment strings. */
|
---|
45 | while (i < argc && strchr(argv[i], '=') != nil) {
|
---|
46 | if (putenv(argv[i]) != 0) {
|
---|
47 | fprintf(stderr, "env: Setting '%s' failed: %s\n",
|
---|
48 | argv[i], strerror(errno));
|
---|
49 | exit(1);
|
---|
50 | }
|
---|
51 | i++;
|
---|
52 | }
|
---|
53 |
|
---|
54 | /* Environment settings and command may be separated with '--'.
|
---|
55 | * This is for compatibility with other envs, we don't advertise it.
|
---|
56 | */
|
---|
57 | if (i < argc && strcmp(argv[i], "--") == 0) i++;
|
---|
58 |
|
---|
59 | if (i >= argc) {
|
---|
60 | /* No utility given; print environment. */
|
---|
61 | char **ep;
|
---|
62 |
|
---|
63 | for (ep= environ; *ep != nil; ep++) {
|
---|
64 | if (puts(*ep) == EOF) {
|
---|
65 | fprintf(stderr, "env: %s\n", strerror(errno));
|
---|
66 | exit(1);
|
---|
67 | }
|
---|
68 | }
|
---|
69 | return 0;
|
---|
70 | } else {
|
---|
71 | char *util, **args;
|
---|
72 | int err;
|
---|
73 |
|
---|
74 | util= argv[i];
|
---|
75 | args= argv + i;
|
---|
76 | if (aflag) args++;
|
---|
77 | (void) execvp(util, args);
|
---|
78 | err= errno;
|
---|
79 | fprintf(stderr, "env: Can't execute %s: %s\n",
|
---|
80 | util, strerror(err));
|
---|
81 | return err == ENOENT ? 127 : 126;
|
---|
82 | }
|
---|
83 | }
|
---|