为什么 Bash 变量在 if 语句内部为空,但在 if 语句外部却不为空?

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

运行 以上结果为:

First name: Bob
Last name: Marley
Last name:

出于某种原因,if 语句中的 LAST_NAME 变量为空。但是,如果我打电话给

echo "Last name: $LAST_NAME"

在脚本有运行后手动我看到:

Last name: Marley

所以,我知道变量实际上包含姓氏。

就好像 if 语句内部的上下文与 if 语句外部的上下文不同一样。那是准确的吗?

我该怎么做才能使这项工作按照我期望的方式进行($LAST_NAME inside the if statement contains the last name)?

我正在 RHEL7 上测试这个。

像这样使用here-doc:

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

EOF1 中使用引号将防止在当前 shell.

中扩展 $ 个变量

根据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 `.

我不确定为什么第一个 echo 语句对你有效而不是第二个 - 当我尝试你的脚本时对我来说都失败了。不过稍作改动,应该可以解决问题。

anubhava 所述,您的变量值将立即执行,不会传递到目标脚本中。您需要使用反斜杠对它们进行转义。此外,没有必要在您的 if 语句中使用 [[ 和 ]]:每一个都可以。单个等号 (=) 也适用于 if 语句。

因此,如果您希望您想要的 variables.sh 脚本是这样的:

#!/bin/bash
echo -n "Please enter your first name: "
read -e -i "Bob" FIRST_NAME
echo -n "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

您应该将初始脚本设为:

cat > variables.sh << EOF1
#!/bin/bash
echo -n "Please enter your first name: "
read -e -i "Bob" FIRST_NAME
echo -n "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

这应该可以解决您的问题。这是我的输出:

Please enter your first name: Bob
Please enter your last name: Marley
First name: Bob
Last name: Marley
Last name: Marley

注意:我还在 echo 语句末尾的引号内添加了“-n”选项和 space。这将禁止换行并允许您在提示符所在的同一行输入答案。