Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to file if exists and create if not

Tags:

bash

echo

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)?

like image 637
Mark Roddy Avatar asked Aug 11 '09 21:08

Mark Roddy


2 Answers

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

like image 128
John Millikin Avatar answered Oct 15 '22 07:10

John Millikin


> 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
like image 24
firstthumb Avatar answered Oct 15 '22 05:10

firstthumb