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"
  • @deenaik post your edit as new question. Do not hijack existing, answered questions.
    – muru
    Apr 4, 2017 at 10:31

3 Answers 3


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

  • 1
    When I do this it appends the echoed string to the last line already in the bashrc file; as in, not on a new line and without a space on the current last line...
    – d8aninja
    Sep 17, 2018 at 17:16
  • 1
    @d8aninja, this would happen if the last line of your file was not terminated with EOL character (0x0A).
    – Alexey
    Nov 7, 2018 at 9:30
  • 1
    What if we want to remove or update a variable from that file?
    – Maf
    Sep 22, 2021 at 17:57

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

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: gh.sh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .