Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you type a tab in a bash here-document?

Tags:

bash

heredoc

tabs

The definition of a here-document is here: http://en.wikipedia.org/wiki/Here_document

How can you type a tab in a here-document? Such as this:

cat > prices.txt << EOF coffee\t$1.50 tea\t$1.50 burger\t$5.00 EOF 

UPDATE:

Issues dealt with in this question:

  1. Expanding the tab character
  2. While not expanding the dollar sign
  3. Embedding a here-doc in a file such as a script
like image 458
D W Avatar asked Sep 16 '10 23:09

D W


2 Answers

TAB="$(printf '\t')"  cat > prices.txt << EOF coffee${TAB}\$1.50 tea${TAB}\$1.50 burger${TAB}\$5.00 EOF 
like image 170
chuck Avatar answered Oct 03 '22 22:10

chuck


You can embed your here doc in your script and assign it to a variable without using a separate file at all:

#!/bin/bash read -r -d '' var<<"EOF" coffee\t$1.50 tea\t$1.50 burger\t$5.00 EOF 

Then printf or echo -e will expand the \t characters into tabs. You can output it to a file:

printf "%s\n" "$var" > prices.txt 

Or assign the variable's value to itself using printf -v:

printf -v var "%s\n" "$var" 

Now var or the file prices.txt contains actual tabs instead of \t.

You could process your here doc as it's read instead of storing it in a variable or writing it to a file:

while read -r item price do     printf "The price of %s is %s.\n" $item $price    # as a sentence     printf "%s\t%s\n" $item $price                  # as a tab-delimited line done <<- "EOF"     coffee $1.50    # I'm using spaces between fields in this case     tea $1.50     burger $5.00     EOF 

Note that I used <<- for the here doc operator in this case. This allows me to indent the lines of the here doc for readability. The indentation must consist of tabs only (no spaces).

like image 36
Dennis Williamson Avatar answered Oct 03 '22 21:10

Dennis Williamson