How do you type a tab in a bash here-document?
You can embed your here doc in your script and assign it to a variable without using a separate file at all:
#!/bin/bashread -r -d '' var<<"EOF"coffee\t$1.50tea\t$1.50burger\t$5.00EOF
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 pricedo printf "The price of %s is %s.\n" $item $price # as a sentence printf "%s\t%s\n" $item $price # as a tab-delimited linedone <<- "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).
For me, I type ctrl-V followed by ctrl-I to insert a tab in the bash shell. This gets around the shell intercepting the tab, which otherwise has a 'special' meaning. Ctrl-V followed by a tab should work too.
When embedding dollar signs in a here document you need to disable interpolation of shell variables, or else prefix each one with a backslash to escape (i.e. \$
).
Using your example text I ended up with this content in prices.txt:
coffee\t.50tea\t.50burger\t.00
because $1
and $5
are not set. Interpolation can be switched off by quoting the terminator, for example:
cat > prices.txt <<"EOF"