Executing Elevated Commands in Your Current Environment

Recently Blake Williams and I were authoring a library for interacting with the Amazon Dash buttons called dashed. For Dashed to work, you need to listen to the requests that your network device can hear on the network it is connected to. This is a restricted device and only can be listened to when you run your commands with elevated privileges (e.g. sudo [command]). Running your command with sudo will give you the proper access. However, since the sudo command runs the subsequent commands in the system user’s environment, it will also be using the system user’s Ruby installation. This can cause issues with gems that are not present, Ruby version differences, and more.

You can solve this in a couple of different ways. For instance you can install all of the gems your project needs in the system user’s environment, and install the correct version of Ruby there as well. What if you want to use an upgraded version of a gem? You’ll have to upgrade all the appropriate gems in your system user’s environment as well. How can you accomplish this in an easy way?

Looking at the output of sudo --help gives you a slew of options. One in particular will solve the problem for us:

-E, --preserve-env          preserve user environment when running command

All you need is the --preserve-env option and all your environment variables will be maintained when executing the elevated command.