Append file contents to the bottom of existing file in Bash

182,370

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Share:
182,370

Related videos on Youtube

Grimlockz
Author by

Grimlockz

Updated on March 18, 2020

Comments

  • Grimlockz
    Grimlockz about 4 years

    Possible Duplicate:
    Shell script to append text to each file?
    How to append output to the end of text file in SHELL Script?

    I'm trying to work out the best way to insert api details into a pre-existing config. I thought about using sed to insert the contents of the api text file to the bottom of the config.inc file. I've started the script but it doesn't work and it wipes the file.

    #!/bin/bash
    
    CONFIG=/home/user/config.inc
    API=/home/user/api.txt
    
    sed -e "\$a $API" > $CONFIG
    

    What am I doing wrong?

  • shellbye
    shellbye over 7 years
    For single string, use echo like this echo "export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_112" >> ~/.bashrc
  • Hans Wouters
    Hans Wouters over 6 years
    Why echo instead of cat?
  • William Pursell
    William Pursell over 6 years
    cat writes the contents of the named files to stdout. echo writes the arguments to stdout. They do different things.
  • PT Huynh
    PT Huynh over 6 years
    Should use 'more' instead of 'cat' as cat will spawn a new process.
  • William Pursell
    William Pursell over 6 years
    @PTHuynh more is a bad choice. The purpose of more is to buffer output to a tty and break it up into sections for interactive human consumption. There is nothing interactive about writing to a file. If some shell has more as a builtin but not cat is an implementation detail.