Shell – How to Append Multiple Lines to a File

io-redirectionshelltext processing

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

Best Answer

# 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