为什么向 bash 脚本添加睡眠似乎会破坏某些命名变量的变量递减?
Why does adding a sleep to a bash script seem to break variable decrementing for certain named variables?
使用以下 bash 脚本:
#!/bin/bash
let SECONDS=5
until [[ "$SECONDS" -le "1" ]]; do
echo SECONDS $SECONDS
(( SECONDS -= 1 ))
# sleep 1
done
我看到了奇怪的行为。也就是说,如果我取消注释 sleep 1
循环继续但计数器 不 递减,我看到如下输出:
$./mvce.sh
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
删除该行会产生预期的结果:
$./mvce.sh
SECONDS 5
SECONDS 4
SECONDS 3
SECONDS 2
我不太确定为什么会这样。我可以将变量重命名为其他名称,事情会按预期工作,所以似乎 sleep
破坏了我的 SECONDS
变量。
这很奇怪,为什么调用 sleep 会覆盖我脚本中的 SECONDS
变量?
SECONDS
是shell中的保留变量。这就是为什么您必须始终在脚本中使用 小写或混合大小写变量 并避免使用所有大写变量名称。
#!/bin/bash
let secs=5
until [[ "$secs" -le "1" ]]; do
echo SECONDS $secs
(( secs -= 1 ))
sleep 1
done
这给出了预期的输出:
SECONDS 5
SECONDS 4
SECONDS 3
SECONDS 2
证明:
SECONDS
Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned
to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value
assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.
使用以下 bash 脚本:
#!/bin/bash
let SECONDS=5
until [[ "$SECONDS" -le "1" ]]; do
echo SECONDS $SECONDS
(( SECONDS -= 1 ))
# sleep 1
done
我看到了奇怪的行为。也就是说,如果我取消注释 sleep 1
循环继续但计数器 不 递减,我看到如下输出:
$./mvce.sh
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
SECONDS 5
删除该行会产生预期的结果:
$./mvce.sh
SECONDS 5
SECONDS 4
SECONDS 3
SECONDS 2
我不太确定为什么会这样。我可以将变量重命名为其他名称,事情会按预期工作,所以似乎 sleep
破坏了我的 SECONDS
变量。
这很奇怪,为什么调用 sleep 会覆盖我脚本中的 SECONDS
变量?
SECONDS
是shell中的保留变量。这就是为什么您必须始终在脚本中使用 小写或混合大小写变量 并避免使用所有大写变量名称。
#!/bin/bash
let secs=5
until [[ "$secs" -le "1" ]]; do
echo SECONDS $secs
(( secs -= 1 ))
sleep 1
done
这给出了预期的输出:
SECONDS 5
SECONDS 4
SECONDS 3
SECONDS 2
证明:
SECONDS
Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.