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.
sudoresets environment variables.sudoexecutes the command as the root user, and/rootis root's home directory. Why don't you expect$HOMEto be updated?--preserve-envoption, but it depends on the permissions enabled insudoers.$HOMEis being expanded in your normal shell, not by the shell run bysudo.sudo bash -c 'echo $HOME'and you'll see the difference.