Writing multi-line text to a file in BASH

In writing bash scripts, you often need to write multi-line configuration files. Here are some ways to do this.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#!/bin/bash # Use echo to redirect text to a file. echo "some data for the file" >> fileName #---------------------------------------------------------- # Use various redirections cat > FILE.txt EOF info code info info code info info code info EOF #---------------------------------------------------------- # Open file descriptor (fd) 3 for read/write on a text file. exec 3> poem.txt # Let's print some text to fd 3 echo "Roses are red" >&3 echo "Violets are blue" >&3 echo "Poems are cute" >&3 echo "And so are you" >&3 # Close fd 3 exec 3>&- cat poem.txt #---------------------------------------------------------- # If you need to do this with root privileges, do it this way: sudo sh -c 'echo "some data for the file" >> fileName' #---------------------------------------------------------- # If you are using variables, you can use: first_var="Hello" second_var="How are you" echo "$first_var> - $second_var>" > ./file_name.txt

This post is licensed under CC BY 4.0 by the author.