HEREDOC operators

Basic usage

VARIABLE="variable"

# command format
cat << CONTENTS > /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
        These are Tabbed
        Indented
CONTENTS

# Result, cat /path/to/output.conf
Normal text here
The second line contains a variable
        These are Tabbed
        Indented

Output alternatives: Can also use >> to append to output file, or | tee to output to screen as it runs.

Quoting preserves content

If you're outputting a script you might need to preserve the variable notation instead of evaluating it. You can use either single or double quotes to do this.

VARIABLE="variable"

# command format
cat << 'CONTENTS' > /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
        These are Tabbed
        Indented
CONTENTS

# Result, cat /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
        These are Tabbed
        Indented

Zapping Tabs

The <<- construct will remove tabs from your input, which means you can format your code nicely. Doesn't work at the same time as "CONTENTS"

VARIABLE="variable"

# command format
cat <<- CONTENTS > /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
	These are Tabbed
		Indented
CONTENTS

# Result, cat /path/to/output.conf
Normal text here 
The second line contains a variable
These are Tabbed
Indented

Leave a Comment