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


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"
  echo -e "export $prop=$val" >> "$rcFile"
  echo "[inserted] export $prop=$val"

Delete environment variable export


prop="POSTGRE_PORT"    # export property to delete

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

For an implementation idea see:

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.