How to append multiple lines to a file

  • I am writing a bash script to look for a file if it doesn't exist then create it and append this to it:

    Host localhost
        ForwardAgent yes
    

    So "line then new line 'tab' then text" I think its a sensitive format. I know you can do this:

    cat temp.txt >> data.txt
    

    But it seems weird since its two lines. Is there a way to append that in this format:

    echo "hello" >> greetings.txt
    
  • # possibility 1:
    echo "line 1" >> greetings.txt
    echo "line 2" >> greetings.txt
    
    # possibility 2:
    echo "line 1
    line 2" >> greetings.txt
    
    # possibility 3:
    cat <<EOT >> greetings.txt
    line 1
    line 2
    EOT
    

    If sudo (other user privileges) is needed to write to the file, use this:

    # possibility 1:
    echo "line 1" | sudo tee -a greetings.txt > /dev/null
    
    # possibility 3:
    sudo tee -a greetings.txt > /dev/null <<EOT
    line 1
    line 2
    EOT
    

    @TheLegend That is called a "here document". Have a look at that paragraph in the man page.

    One more possibility is `( echo "line 1" ; echo "line 2" ) >>greetings.txt`.

    @ott-- You don't need a real subshell (i.e. can save one new process), this is enough: `{ echo "line 1" ; echo "line 2"; } >>greetings.txt`

    Indeed, `{}` is the better idea.

    Bash's built-in `echo` supports `-e`, so that's another possibility. Also, `$'line1\nline2\nline3'` is another bash feature.

    whts the difference between EOT and EOL?

    @cikatomo In `cat <

    Question: won't option 3 be subject to tab completion and variable replacement making it unreliable? Also I've seem some people use `cat <

    @TCB13 Whether the `EOT` is quoted (somehow) determines whether parameter expansion, command substitution, and arithmetic expansion are applied to the lines.

    @HaukeLaging what if one doesn't one any kind of parameter expansion? Just the lines going into the file?

    @TCB13 `cat <<"EOT" ... EOT` prevents expansion of parameters and shell variables.

    @cikatomo fyi, `EOT, EOL, EOF` acronyms stand for `end of transmission/line/file` respectively

    How to write multi-line script without it being evaluated ? `<

    @AlexandreA. From the man page, slightly modified: If any part of EOT is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded." So use e.g. `<<"EOT"` Now that I have written this I notice that this has been answered already, to comments before yours.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM