Write multi-line file in shell scripting

Hi everybody. In this post I will just explain how to write multi-line files with bash using cat. I write this post because I am not an expert with Shell scripting and recently, I needed to create ldif files from a shell script. I will explain my old and bad method, and the new one that I am using now.

Main goal

From a shell script, I want to create a ldif file on my disk that contains somethings like this:

dn: cn=config
changetype: modify
add: olcDisallows
olcDisallows: bind_anon
-

dn: olcDatabase={-1}frontend,cn=config
changetype: modify
add: olcRequires
olcRequires: authc

Old method with echo

This method is the most “evident” for beginner like me.

touch myfile.ldif
echo "dn: cn=config" >> myfile.ldif
echo "changetype: modify" >> myfile.ldif
echo "add: olcDisallows" >> myfile.ldif
echo "olcDisallows: bind_anon" >> myfile.ldif
echo "-" >> myfile.ldif
echo "" >> myfile.ldif
echo "dn: olcDatabase={-1}frontend,cn=config" >> myfile.ldif
echo "changetype: modify" >> myfile.ldif
echo "add: olcRequires" >> myfile.ldif
echo "olcRequires: authc" >> myfile.ldif

This syntax is easy but a little repetitive because for each line we need to repeat the “>>” and the file name.

New method with cat

This method is very useful

cat > myfile.ldif <<EOL
dn: cn=config
changetype: modify
add: olcDisallows
olcDisallows: bind_anon
-

dn: olcDatabase={-1}frontend,cn=config
changetype: modify
add: olcRequires
olcRequires: authc
EOL

The reading is really more clear. The content of the file can be read easily. The syntax is not really more complex. We just need to remember this block of code:

cat > theFile <<EOL
line 1
line 2
...
line n
EOL

Probably that for regulars and scripting guru this post is completely useless but I think it serves good reminder for the next time :-). If you know other method or have more information about this topic, please write a comment 🙂

Bookmark the permalink.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.