1

I'm running a GCE VM with Ubuntu 18, and having an issue with a perl command.

export ip_addr=`hostname -i`
echo "set \$ip_addr_priv \"{my_ip_address}\"" | sudo perl -n -e 's/(\$ip_addr_priv) +"\{([a-zA-Z0-9_]+)\}"/\1 "$ENV{ip_addr}"/g; print;'

When I run this in the command line, I get the following output:

set $ip_addr_priv ""

Instead of something like this:

set $ip_addr_priv "127.0.0.1"

What am I doing wrong?

ObiHill
  • 11,448
  • 20
  • 86
  • 135
  • 2
    Maybe the environment variable is not exported into the `sudo` environment? See also [How to keep environment variables when using sudo?](https://stackoverflow.com/q/8633461/2173773) – Håkon Hægland Oct 28 '19 at 10:52

1 Answers1

3

By default (and by design), sudo doesn't pass the current user's environment on to the new process.

You can override this behaviour with the -E command line flag.

echo "set \$ip_addr_priv \"{my_ip_address}\"" | sudo perl -n -e 's/(\$ip_addr_priv) +"\{([a-zA-Z0-9_]+)\}"/\1 "$ENV{ip_addr}"/g; print;'
set $ip_addr_priv ""

Vs:

echo "set \$ip_addr_priv \"{my_ip_address}\"" | sudo -E perl -n -e 's/(\$ip_addr_priv) +"\{([a-zA-Z0-9_]+)\}"/\1 "$ENV{ip_addr}"/g; print;'
set $ip_addr_priv "127.0.1.1"
Dave Cross
  • 68,119
  • 3
  • 51
  • 97