1// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
2//
3//  Copyright (c) 2001-2003, Haiku
4//
5//  This software is part of the Haiku distribution and is covered
6//  by the MIT License.
7//
8//
9//  File:        printenv.c
10//  Author:      Daniel Reinhold (danielre@users.sf.net)
11//  Description: prints environment variables
12//
13// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
14
15#include <OS.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19
20
21extern char **environ;
22
23int print_env(char *);
24
25
26int
27main(int argc, char *argv[])
28{
29	char *arg = (argc == 2 ? argv[1] : NULL);
30
31	if ((argc > 2) || (arg && !strcmp(arg, "--help"))) {
32		printf("Usage: printenv [VARIABLE]\n"
33		       "If no environment VARIABLE is specified, print them all.\n");
34		return 1;
35	}
36
37	return print_env(arg);
38}
39
40
41int
42print_env(char *arg)
43{
44	char **env = environ;
45
46	if (arg == NULL) {
47		// print all environment 'key=value' pairs (one per line)
48	    while (*env)
49			printf("%s\n", *env++);
50
51		return 0;
52	} else {
53		// print only the value of the specified variable
54		char *s;
55		int   len   = strlen(arg);
56		bool  found = false;
57
58	    while ((s = *env++) != NULL)
59	    	if (!strncmp(s, arg, len)) {
60	    		char *p = strchr(s, '=');
61	    		if (p) {
62					printf("%s\n", p+1);
63					found = true;
64				}
65			}
66
67		return (found ? 0 : 1);
68	}
69}
70