21

I am working on a bash script that needs to take a single line and add it to the end of a file if it exists, and if it does not exist create the file with the line.

I have so far:

    if [ ! -e /path/to/file ]; then
        echo $some_line > /path/to/file
    else
        ???
    fi

How do I perform the operation that should go in the else (adding the line of text to the existing file)?

thedp
  • 8,350
  • 16
  • 53
  • 95
Mark Roddy
  • 27,122
  • 19
  • 67
  • 71

2 Answers2

33

Use two angles: echo $some_line >> /path/to/file

John Millikin
  • 197,344
  • 39
  • 212
  • 226
23

> creates the file if it doesn't exist; if it exists, overwrites it.

>> creates the file if it doesn't exist; if it exists, appends to it.

if [ ! -e /path/to/file ]; then
   echo $some_line > /path/to/file
else
   echo $some_line >> /path/to/file
fi
approxiblue
  • 6,982
  • 16
  • 51
  • 59
firstthumb
  • 4,627
  • 6
  • 35
  • 45