bashtabsheredoc

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


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

Solution

  • 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).