Home > Net >  Why are some variables inside single quote not escaped in Bash?
Why are some variables inside single quote not escaped in Bash?

Time:11-26

#!bin/bash

outfile="members.sql"
IFS=','

while read lname fname address city state zip; do
    cat >> $outfile << EOF
    INSERT INTO members (lname,fname,address,city,state,zip) VALUES
    ('$lname', '$fname', '$address', '$city', '$state', '$zip');
EOF
done < ${1}

The input file is a .csv file with data like Blum,Richard,123 Main St.,Chicago,IL,60601.

Why does this code work? As I know, everything inside a single quote are taken literally right? Why are these variables be substituted?

My guess is that it's a two-step process, first it WAS taken literally when the STDIN redirection happened, and then it IS SUBSTITUTED when appended into the outfile, am I close? How does this actually work?

CodePudding user response:

Inside a here document ' means literally '. It has no special meaning.

$ cat <<EOF
> '
> EOF
'

is that it's a two-step process

I would say it's one step. You take all lines between here doc delimiter <<EOF and EOF and then do variable expansion on $strings and then output. You can read about it in documentation https://www.gnu.org/software/bash/manual/bash.html#Here-Documents :

[...] all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.

  • Related