Unix Environment Variable Scope/Security

I recently encountered a command line tool which exposed passwords in the process listing.

The command would also also accept a password as an environment variable. I was concerned with the security of storing a password in an environment variable.

This article at itworld.com does a nice job explaining environment variable scope.

Environment variables are only accessible in the shell in which they are set.

If you export the variable, it is accessible to any subshell of the shell in which it is exported. Simply logging in as another user on the system or even the same user does not allow access to the exported variable.

So, until someone corrects me, I believe that setting and exporting environment variables containing passwords in a script does protect the password from exposure. As soon as the command requiring the password has completed, the variable can be reset to an empty string to prevent any further access to the password.

convert lines to comma separated items with tr

If you have output that is separated by new lines, but you really want it formatted into a single line with commas as separators or maybe a space as a separator, just pipe to tr.

Here is a simple example:

kserver:~ patternbuffer$ diskutil list | grep ^/dev
/dev/disk0
/dev/disk1

If we want them separated by spaces, we could do:

kserver:~ patternbuffer$ diskutil list | grep ^/dev | tr '\n' ' '
/dev/disk0 /dev/disk1

Note that there is a newline on the end of the output, so that trailing newline is also translated. So if you don’t want it there, you’ll have to chomp it off. I use sed, but use what you like.

Here is the same as above, but with commas, with sed to remove the trailing comma.

kserver:~ patternbuffer$ diskutil list | grep ^/dev | tr '\n' ',' | sed 's/.$//'
/dev/disk0,/dev/disk1