0

I have a bash script wich I need to add a system enviroment variable accessible for all users and it should be permanent. I tried:

#!/bin/bash
$EDITOR ~/.profile
export MY_VAR="123"

But Im getting the error : line 2: /root/.profile: Permission denied even if I execute it as root.

  • Why are you working with /root/.profile, they exist a /etc/profile for that! – George Udosen Jan 12 '18 at 17:43
1

The error you are getting is likely because EDITOR is not set - so your command becomes

~/.profile

which tries to execute the .profile of the invoking user (clearly root in this case).

Even if set $EDITOR usually points to an interactive text editor - it's not going to magically take the following line and insert it in the file. In any case /root/.profile is the personal .profile file for user root - no help if you want to modify the system-wide environment.

To make a system-wide change, you should modify either /etc/profile or /etc/environment1 - or (better) create a custom file in the /etc/profile.d/ directory e.g.

echo 'export MY_VAR="123"' >> /etc/profile.d/myvars

Your script will of course need to be run as root e.g. using sudo


[1] note that if you use /etc/environment, remove the export (variables in this file are just defined as simple name=value pairs)

|improve this answer|||||
  • It worked, but only after I restart the OS, is there a way to update this variable without restarting the machine? Thanks! – gog Jan 12 '18 at 18:22
  • 1
    @gog not as far as I know - processes inherit their environment when they're started, I'm not aware of any way to "push" a new value to them – steeldriver Jan 12 '18 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.