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

标签 linux bash shell rhel7

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

关于linux - 为什么 Bash 变量在 if 语句内为空,但在 if 语句外却不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759896/

相关文章:

linux - 自动复制文件

regex - 如何在 bash 中替换字符串中的空格和斜杠?

linux - 下载某种类型的所有文件,不带目录

linux - 使用一个文件中的部分列作为另一个文件中的搜索词

bash - 查找并打印列值重复 n 次的行

linux - Whiptail 没有运行我的 bash 命令

node.js - 我无法在 ubuntu 上安装 nodejs 8

c - 如何为多个进程实现管道?

bash - crontab 提取cron表达式

linux - 使用 grep 提取值