gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:47 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com