coreutils

General Software Utilities
git clone http://git.omkov.net/coreutils
Log | Tree | Refs | README | LICENCE | Download

coreutils/src/env.c (66 lines, 1.5 KiB) -rw-r--r-- blame download

01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
// env.c, version 1.0.2
// OMKOV coreutils implementation of POSIX env
// Copyright (C) 2020, Jakob Wakeling
// MIT Licence

#include "util/error.h"
#include "util/optget.h"

#include <unistd.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define VERSION "1.0.2"

static struct lop lops[] = {
	{ "help",    ARG_NUL, 256 },
	{ "version", ARG_NUL, 257 },
	{ NULL, 0, 0 }
};

extern char **environ;

static void hlp(void);
static void ver(void);

int main(int ac, char *av[]) { (void)ac; A0 = av[0];
	struct opt opt = OPTGET_INIT; opt.str = "i"; opt.lops = lops;
	for (int o; (o = optget(&opt, av, 0)) != -1;) switch (o) {
	case 'i': { environ = NULL; break; }
	case 256: { hlp(); return 0; }
	case 257: { ver(); return 0; }
	default: { return 1; }
	}
	
	register char **p = &av[opt.ind];
	for (; *p && strchr(*p, '='); ++p) { putenv(*p); }
	
	if (!*p) {
		if (environ) for (char **v = environ; *v; ++v) { puts(*v); }
		return 0;
	}
	
	execvp(*p, &*p);
	
	warn("%s: %s", *p, serr());
	return errno = ENOENT ? 127 : 126;
}

static void hlp(void) {
	puts("env - execute with an altered enviroment\n");
	puts("usage: env [-i] [name=value]... [command [argument...]]\n");
	puts("options:");
	puts("  -i         Ignore inherited enviroment");
	puts("  --help     Display help information");
	puts("  --version  Display version information");
}

static void ver(void) {
	puts("OMKOV coreutils env, version " VERSION);
	puts("Copyright (C) 2020, Jakob Wakeling");
	puts("MIT Licence (https://opensource.org/licenses/MIT)");
}