>From 0ed502c97c5b1dd51dc323e3f1354db99d1ab46f Mon Sep 17 00:00:00 2001 From: Gianluca Mascolo <gianl...@gurutech.it> Date: Sun, 11 Dec 2022 18:02:20 +0100 Subject: [PATCH] printenv: add feature to print names only
--- src/printenv.c | 13 +++++++++++-- tests/misc/printenv.sh | 3 +++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/printenv.c b/src/printenv.c index 0b178bedd..47eff3c91 100644 --- a/src/printenv.c +++ b/src/printenv.c @@ -47,6 +47,7 @@ enum { PRINTENV_FAILURE = 2 }; static struct option const longopts[] = { {"null", no_argument, NULL, '0'}, + {"names-only", no_argument, NULL, 'n'}, {GETOPT_HELP_OPTION_DECL}, {GETOPT_VERSION_OPTION_DECL}, {NULL, 0, NULL, 0} @@ -68,6 +69,7 @@ If no VARIABLE is specified, print name and value pairs for them all.\n\ program_name); fputs (_("\ -0, --null end each output line with NUL, not newline\n\ + -n, --names-only output only variable name, not value\n\ "), stdout); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); @@ -86,6 +88,7 @@ main (int argc, char **argv) bool ok; int optc; bool opt_nul_terminate_output = false; + bool opt_names_only = false; initialize_main (&argc, &argv); set_program_name (argv[0]); @@ -96,13 +99,16 @@ main (int argc, char **argv) initialize_exit_failure (PRINTENV_FAILURE); atexit (close_stdout); - while ((optc = getopt_long (argc, argv, "+iu:0", longopts, NULL)) != -1) + while ((optc = getopt_long (argc, argv, "+iu:0n", longopts, NULL)) != -1) { switch (optc) { case '0': opt_nul_terminate_output = true; break; + case 'n': + opt_names_only = true; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: @@ -113,7 +119,10 @@ main (int argc, char **argv) if (optind >= argc) { for (env = environ; *env != NULL; ++env) - printf ("%s%c", *env, opt_nul_terminate_output ? '\0' : '\n'); + printf ("%.*s%c", + opt_names_only ? ((int) (strchr(*env,'=') - *env)) : ((int) strlen(*env)), + *env, + opt_nul_terminate_output ? '\0' : '\n'); ok = true; } else diff --git a/tests/misc/printenv.sh b/tests/misc/printenv.sh index 6cee5e7de..d97277fa1 100755 --- a/tests/misc/printenv.sh +++ b/tests/misc/printenv.sh @@ -58,6 +58,9 @@ b EOF compare exp out || fail=1 +# Print only variable names +env -i ENV_TEST=hidden PATH="$PATH" printenv | grep -qF hidden && fail=1 + # Exit status reflects missing variable, but remaining arguments processed. export ENV_TEST1=a returns_ 1 env -- printenv ENV_TEST2 ENV_TEST1 > out || fail=1 -- 2.34.1