Add environment variable to .bashrc through script

I need to add the following lines to the end of .bashrc file in Ubuntu. How can I add these lines automatically using a script. If I run the script, then it automatically inserts the lines at the end of .bashrc file.

export APP="/opt/tinyos-2.x/apps"
export TOS="/opt/tinyos-2.x/tos"
Asked By: ManiAm

||

Use the echo command to append lines to the .bashrc script

So in your script use these lines

echo 'export APP=/opt/tinyos-2.x/apps' >> ~/.bashrc 

echo  'export TOS=/opt/tinyos-2.x/tos' >> ~/.bashrc 

Make sure to use >> (append), if you use a single > you will overwrite the file.

~/.bashrc indicates .bashrc is in your home directory

Answered By: dcolhoun

Just an addition to above answers. If someone wants to export variables they can also use the below format. Hope it helps. =)

echo 'export PATH="${HOME}/soft:${PATH}"' >> ~/.bashrc
Answered By: Muhammad Ali

Here’s a more flexible way to achieve the desired:

Insert or update environment variable export

rcFile="~/.bashrc"

prop="WAYLAND_DISPLAY"   # export property to insert
val="wayland-1"          # the desired value

if grep -q "^export $prop=" "$rcFile"; then
  sed -i "s/^export $prop=.*$/export $prop=$val/" "$rcFile" &&
  echo "[updated] export $prop=$val"
else
  echo -e "export $prop=$val" >> "$rcFile"
  echo "[inserted] export $prop=$val"
fi

Delete environment variable export

rcFile="~/.bashrc"

prop="POSTGRE_PORT"    # export property to delete

if grep -q "^export $prop=" "$rcFile"; then
  sed -i "/^export $prop=.*$/d" "$rcFile" &&
  echo "[deleted] export $prop"
else
  echo "[not found] export $prop"
fi

For an implementation idea see: gh.sh

Answered By: Roko C. Buljan
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.