In a posix-compatible way that works with multiple implementations, how can I print the list of currently defined environment variable without their values?
On some implementations (mksh, freebsd /bin/sh), just using export
by itself will fit the bill:
$ export
FOO2
FOO
But for some other implementations (bash, zsh, dash), export
also shows the value. With bash, for example:
$ export
export FOO2='as df\
asdk=fja:\
asd=fa\
asdf'
export FOO='sjfkasjfd kjasdf:\
asdkj=fkajdsf:\
:askjfkajsf=asdfkj:\
safdkj'
$ printenv | sed -n l
FOO2=as\tdf\$
asdk=fja:\$
asd=fa\$
asdf$
FOO=sjfkasjfd kjasdf:\$
asdkj=fkajdsf:\$
\t:askjfkajsf=asdfkj:\$
safdkj$
Other options like env
or printenv
don't have options to print just the variable names without values, at least not on the linux and freebsd platforms I have tried.
Piping to awk/sed/etc. or trimming the list with parameter expansion techniques (e.g., ${foo%%=*}
) is acceptable, but it has to work with values that may span lines and have =
and whitespace in the value (see example above).
Answers specific to particular shell implementations are interesting, but I am primarily looking for something that is compatible across implementations.
export -p
which is specified by POSIX to generate output that is also suitable for input in the shell. – Kusalananda♦ Apr 21 '18 at 16:01export -p
for this? – Juan Apr 21 '18 at 17:22export -p
because that would give you a consistent output across all POSIX shells, which you said you wanted. – Kusalananda♦ Apr 21 '18 at 17:25export -p
does not fit the first requirement - printing just variable names without values. – Juan Apr 21 '18 at 17:30export -p
. I'm not going to write that parsing, because in the general case, it would have to also do proper quote parsing, in case you have a variable whose value is something likehello\nexport var=value
. One of the few other commands that will give you consistent output in all POSIX shells isenv
, but that output is harder to parse since it lacks theexport =
bit. – Kusalananda♦ Apr 21 '18 at 18:11