Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print environment variables sorted by name including variables with newlines

I couldn't find an existing answer to this specific case: I would like to simply display all exported environment variables sorted by their name. Normally I can do this like simply like:

$ env | sort

However, if some environment variables contain newlines in their values (as is the case on the CI system I'm working with), this does not work because the multi-line values will get mixed up with other variables.

like image 579
Iguananaut Avatar asked Mar 19 '20 11:03

Iguananaut


Video Answer


2 Answers

Answering my own question since I couldn't find this elsewhere:

$ env -0 | sort -z | tr '\0' '\n'

env -0 separates each variable by a null character (which is more-or-less how they are already stored internally). sort -z uses null characters instead of newlines as the delimiter for fields to be sorted, and finally tr '\0' '\n' replaces the nulls with newlines again.

Note: env -0 and sort -z are non-standard extensions provided by the GNU coreutils versions of these utilities. Open to other ideas for how to do this with POSIX sort--I'm sure it is possible but it might require a for loop or something; not as easy as a one-liner.

like image 146
Iguananaut Avatar answered Nov 02 '22 23:11

Iguananaut


The bash builtin export prints a sorted list of envars:

export -p | sed 's/declare -x //'

Similarly, to print a sorted list of exported functions (without their definitions):

export -f | grep 'declare -fx' | sed 's/declare -fx //' 
like image 43
smoors Avatar answered Nov 03 '22 00:11

smoors