1

I'm writing a script that needs to be run with sudo, and have run into something curious and wondered if anyone could explain it...

My environment variable seems not to behave the same when in ruby vs when in shell:

user@server:~$ sudo echo $HOME
/home/user

user@server:~$ sudo /opt/ruby-2.1.2-p95/bin/irb
irb(main):002:0> puts ENV['HOME']
/root
=> nil
irb(main):003:0>

What could be the cause of this?

Edit: To clarify - I'm not asking why sudo is resetting my env variable, I'm asking why it does't when I run shell commands/scripts (1st command), but it does when I run ruby (2nd command) from the same shell session without any change in configuration.

7
  • sudo resets environment variables. Commented Apr 15, 2016 at 22:27
  • sudo executes the command as the root user, and /root is root's home directory. Why don't you expect $HOME to be updated? Commented Apr 15, 2016 at 22:30
  • You could try using the --preserve-env option, but it depends on the permissions enabled in sudoers. Commented Apr 15, 2016 at 22:31
  • 3
    In your first command, $HOME is being expanded in your normal shell, not by the shell run by sudo. Commented Apr 15, 2016 at 22:43
  • 1
    Try: sudo bash -c 'echo $HOME' and you'll see the difference. Commented Apr 15, 2016 at 22:44

1 Answer 1

2

By default, sudo resets your environment variables. You might be able to use sudo's --preserve-env (or -E for short) to preserve the environment. You can run man sudo to learn more about sudo and its options.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.