Search code examples
linuxbashshellrhel7

Why is a Bash variable empty inside of an if statement empty, but not outside of the if statement?


cat > variables.sh << EOF1
#!/bin/bash
echo "Please enter your first name:"
read -e -i "Bob" FIRST_NAME
echo "Please enter your last name:"
read -e -i "Marley" LAST_NAME

echo "First name: $FIRST_NAME"
echo "Last name: $LAST_NAME"
if [[ "$FIRST_NAME" == "Bob" ]] ; then
echo "Last name: $LAST_NAME"
fi
EOF1
source ./variables.sh

Running the above results in:

First name: Bob
Last name: Marley
Last name:

For some reason, the LAST_NAME variable inside of the if statement is empty. But, if I call

echo "Last name: $LAST_NAME"

manually after the script has run I see:

Last name: Marley

So, I know the variable actually contains the last name.

It is acting as if the context inside of the if statement is different than the context outside of the if statement. Is that accurate?

What can I do to make this work the way I would expect ($LAST_NAME inside of the if statement contains the last name)?

I am testing this on RHEL7.


Solution

  • Use here-doc as this:

    cat > variables.sh <<-'EOF1'
    #!/bin/bash
    echo "Please enter your first name:"
    read -e -i "Bob" FIRST_NAME
    echo "Please enter your last name:"
    read -e -i "Marley" LAST_NAME
    
    echo "First name: $FIRST_NAME"
    echo "Last name: $LAST_NAME"
    if [[ "$FIRST_NAME" == "Bob" ]] ; then
    echo "Last name: $LAST_NAME"
    fi
    EOF1
    

    Using quotes in EOF1 will prevent expansion of $ variables in current shell.

    As per man bash:

    No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \ is ignored, and \ must be used to quote the characters \, $, and `.