wc: Added wc
[mutos-utils.git] / env.c
blob527b6981b924d5e29a0913a95063b1e757ad6b9c
1 /*
2 Copyright © 2013 Alastair Stuart
4 This program is open source software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
15 #include <stdio.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <errno.h>
20 #include <unistd.h>
22 #define VERSION "0.01"
24 extern char **environ;
26 int main(int argc, char* argv[])
28 // flag parsing
29 int arg = 0;
30 for (arg = 1; arg < argc; arg++)
32 if (strcmp("--help", argv[arg]) == 0 || strcmp("-h", argv[arg]) == 0) {
33 printf("Usage: %s [name=value ...] [command]\n", argv[0]);
34 printf("\n"
35 "If no command is given, all environment variables are listed.\n"
36 "\n"
37 " --help Print this message.\n"
38 " --version Show version info.\n");
39 return 0;
40 } else if (strcmp("--version", argv[arg]) == 0 || strcmp("-v", argv[arg]) == 0) {
41 printf("env (mutos) v"VERSION"\n");
42 return 0;
43 } else {
44 // no more flags
45 break;
49 // parse the key-value pairs
50 for ( ; arg < argc; arg++)
52 // find the equals
53 char* equals = strchr(argv[arg], '=');
54 // if there's no equals, it must be a command
55 if (!equals) {
56 break;
58 // delete it
59 *equals = '\0';
60 char* name = argv[arg];
61 // the value string starts right after the equals
62 char* value = equals + 1;
63 setenv(name, value, 1);
66 // parse command
67 size_t total_len = 0;
68 for (int i = arg; i < argc; i++)
70 total_len += strlen(argv[i]) + 1;
73 char* command = NULL;
74 if (arg < argc) {
75 command = calloc(total_len, sizeof(char));
78 for (int i = arg; i < argc; i++)
80 strcat(command, argv[i]);
81 if (i != argc - 1) {
82 strcat(command, " ");
86 if (arg < argc) {
87 command[total_len - 1] = '\0';
90 if (command) {
91 system(command);
92 } else {
93 for (char **env = environ; *env; ++env)
95 printf("%s\n", *env);
99 return 0;