bash 中带引号和不带引号的相同值相等
Equality for same value with and without quotes in bash
我有这个代码
#!/bin/bash
today=$(date +'%Y-%m-%d')
date_in_config=$(cat config.json | jq ".date")
echo $date_in_config
echo $today
if [ $date_in_config == $today ];then
echo "Same date"
else
echo "different"
fi
config.json
{
"date": "2021-03-24",
"session": "0"
}
我一直在比较日期。我从上面的代码得到的输出是
"2021-03-24"
2021-03-24
different
我做错了什么?
显然您已经发现问题所在:对于 Bash(以及我能想到的任何其他编程语言),"x"
与 x
不同。
把双引号放在today
:
today=$(date +'"%Y-%m-%d"')
或检索JSON信息时去掉引号:
date_in_config=$(jq -r ".date" < config.json)
并记得引用您的变量扩展,如 Shellcheck would have told you. Also get rid of the ==
bashism(可选,为了便于携带)。
[ "$date_in_config" = "$today" ]
我有这个代码
#!/bin/bash
today=$(date +'%Y-%m-%d')
date_in_config=$(cat config.json | jq ".date")
echo $date_in_config
echo $today
if [ $date_in_config == $today ];then
echo "Same date"
else
echo "different"
fi
config.json
{
"date": "2021-03-24",
"session": "0"
}
我一直在比较日期。我从上面的代码得到的输出是
"2021-03-24"
2021-03-24
different
我做错了什么?
显然您已经发现问题所在:对于 Bash(以及我能想到的任何其他编程语言),"x"
与 x
不同。
把双引号放在
today
:today=$(date +'"%Y-%m-%d"')
或检索JSON信息时去掉引号:
date_in_config=$(jq -r ".date" < config.json)
并记得引用您的变量扩展,如 Shellcheck would have told you. Also get rid of the ==
bashism(可选,为了便于携带)。
[ "$date_in_config" = "$today" ]