Ubuntu – `setx` equivalent in Ubuntu

bashcommand lineenvironment-variables

Windows has a powershell command called setx which Creates or modifies environment variables in the user or system environment.

Does Ubuntu has a similar command, i.e. not by using nano or vi, just one line to add or update an environment variable system wide.

Implemented Solution

One line to add/update

grep env_name /etc/environment && sed -i.bak 's/env_name=.*/env_name="env_value"/' /etc/environment || echo 'env_name="env_value"' >> /etc/environment

Best Answer

  • You can do this simply by declaring it as new in the command line or re-declaring it. For example, if you want to add ~/testfolder to your path variable, you simply can enter it in your current terminal (this is just an example):

    PATH="$HOME/testfolder:$PATH"
    

    This will of course only change it for the time you have said terminal session open. Notice the $ usage here, you leave it out for declaration, but if you want to display it you need to add $ to expand its contents.

    If you want to declare them more lasting and general you can add them into your ~/.bashrc (only for you) file or in /etc/bash.bashrc (system wide) for example if you want them to be counting for only you or for all users. Another option is to add it to your .profile file (only for yourself) where it will be viable from the moment you log in. You can do this with echo for example if you're sure this variable is not set already or if you create new ones (only an example):

    echo "variable=value" >> /path/filename
    

    If you however want to edit a file outside your user directory which is the case when you want to edit /etc/bash.bashrc you need to use sudo and so you cant simply use a 'here document' since this would not work, instead use then a line like below:

    echo "variable=value" | sudo tee -a /path/filename
    

    If the variable however already exists you can change it with the sed command (also only an example):

    sed -i.bak 's/variable=value/variable=new-value/' /path/filename
    

    This will edit the variable in file but create a backup of it prior to the edit. If you change files outside your user directory with sed you need to use sudo in most cases so the line would be:

    sudo sed -i.bak 's/variable=value/variable=new-value/' /path/filename
    

    Removing a variable from a file can be done with sed as well, just leave the second part of the regex empty:

    sed -i.bak 's/variable=value//' /path/filename
    

    If your interested which environment variables are set you can use the env command to list them, ( set -o posix ; set ) | less or sh -c set. All three give various amounts of output, with ( set -o posix ; set ) | less giving back the most variables which are actually set.