Skip to content

Instantly share code, notes, and snippets.

@pykong
Last active May 9, 2023 12:06
Show Gist options
  • Save pykong/ce315dff7ac052ee3b454010af026539 to your computer and use it in GitHub Desktop.
Save pykong/ce315dff7ac052ee3b454010af026539 to your computer and use it in GitHub Desktop.
Script to permanently set environment variables under Linux (Ubuntu 16.04 and later). Run as sudo. Usage: sudo set_env_var.sh key value
#!/bin/bash
# run under sudo
# script for permanently setting environment variables, found here:
# https://stackoverflow.com/questions/13046624/how-to-permanently-export-a-variable-in-linux
add_env_var()
{
KEY=$1
VALUE=$2
echo "export "$KEY"="$VALUE>>~/.bashrc
echo $KEY"="$VALUE>>~/.profile
echo $KEY"="$VALUE>>/etc/environment
source ~/.bashrc
source ~/.profile
}
if [ "$(id -u)" != "0" ]; then
echo "Sorry, you are not sudo."
exit 1
fi
add_env_var() $1 $2
exit
@andresgomes1855
Copy link

what if I run this script multiple times? My VARS will be duplicated

@andresgomes1855
Copy link

Maybe add this:

sed -i '/$KEY/d' ~/.bashrc
sed -i '/$KEY/d' ~/.profile
sed -i '/$KEY/d' /etc/environment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment