xref: /haiku/src/bin/printenv.c (revision bc3955fea5b07e2e94a27fc05e4bb58fe6f0319b)
1 // ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
2 //
3 //  Copyright (c) 2001-2003, OpenBeOS
4 //
5 //  This software is part of the OpenBeOS distribution and is covered
6 //  by the OpenBeOS 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 
21 extern char **environ;
22 
23 int print_env(char *);
24 
25 
26 int
27 main(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 
41 int
42 print_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