returns exit status 1 on failure and allows multiple matches

git-svn-id: file:///srv/svn/repos/haiku/trunk/current@1459 a95241bf-73f2-0310-859d-f6bbb57e9c96
This commit is contained in:
Daniel Reinhold
2002-10-08 19:03:36 +00:00
parent 9c47418b7c
commit 96b225d3ec
+22 -29
View File
@@ -12,7 +12,7 @@
// //
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ // ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
#include <OS.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@@ -20,58 +20,51 @@
extern char **environ; extern char **environ;
void print_env(char *); int print_env(char *);
void
usage()
{
printf("usage: printenv [VARIABLE]\n"
"If no environment VARIABLE is specified, print them all.\n");
}
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
if (argc > 2) char *arg = (argc == 2 ? argv[1] : NULL);
usage();
else { if ((argc > 2) || (arg && !strcmp(arg, "--help"))) {
char *arg = (argc == 2 ? argv[1] : NULL); printf("usage: printenv [VARIABLE]\n"
"If no environment VARIABLE is specified, print them all.\n");
if (arg && !strcmp(arg, "--help")) return 1;
usage();
print_env(arg);
} }
return 0; return print_env(arg);
} }
void int
print_env(char *arg) print_env(char *arg)
{ {
char **env = environ; char **env = environ;
if (arg) { if (arg == NULL) {
// print all environment 'key=value' pairs (one per line)
while (*env)
printf("%s\n", *env++);
return 0;
}
else {
// print only the value of the specified variable // print only the value of the specified variable
char *s; char *s;
int len = strlen(arg); int len = strlen(arg);
bool found = false;
while ((s = *env++) != NULL) while ((s = *env++) != NULL)
if (!strncmp(s, arg, len)) { if (!strncmp(s, arg, len)) {
char *p = strchr(s, '='); char *p = strchr(s, '=');
if (p) { if (p) {
printf("%s\n", p+1); printf("%s\n", p+1);
break; found = true;
} }
} }
}
else { return found ? 0 : 1;
// print all environment 'key=value' pairs (one per line)
while (*env)
printf("%s\n", *env++);
} }
} }