在计算中用变量替换硬编码值

时间:2019-08-27 14:33:09

标签: bash

在使用$((($(date -f - +%s- <<<$'10:20 tomorrow\nnow')0)%86400))计算经过时间时,我想用一个变量替换硬编码的时间,但是我尝试过的任何反斜杠都是重复的,并且该公式无效。我在这里想念什么?

我尝试将变量放在引号中,将变量周围的单引号引起来,而不将$放在变量前面。

硬编码:

currenttime=$( date '+%H:%M:%S' )
echo currenttime = $currenttime
starttime="10:20:00"
echo elapsed seconds = $((($(date -f - +%s- <<<$'10:20 tomorrow\nnow')0)%86400))

使用变量:

echo currenttime = $currenttime
starttime="10:20:00"
echo elapsed seconds = $((($(date -f - +%s- <<<$'$starttime tomorrow\nnow')0)%86400))

硬编码结果:

currenttime = 15:28:54
经过的秒数= 67866

currenttime = $(date'+%H:%M:%S')

可变结果:

currenttime = 15:30:03
日期:无效日期â$ starttime明天“
经过的秒数= 52203

1 个答案:

答案 0 :(得分:3)

$'...'不执行参数扩展;您需要在该部分使用双引号。

例如:

echo elapsed seconds = $((($(date -f - +%s- <<<"$starttime tomorrow"$'\n'"now")0)%86400))

但是,将其分成几行代码会更加简单:

now=$(date +%s)
later=$(date +%s --date "$starttime tomorrow")
echo "elapsed seconds = $(( (later - now) % 86400 ))"

或使用here文档进行多行输入:

x=$(( $(date -f- +%s- <<EOF
$starttime tomorrow
now
EOF
)0 % 86400))