【发布时间】:2019-02-22 23:03:22
【问题描述】:
说明
你好,
我有一个 bash 脚本,它通过在 /usr/local/bin/ 中找到某些命令并执行它们来循环它们。命令给出的输出只是数字,我们获取这些数字,将它们存储在文件中,如果它们之间的时间差超过半小时,则将当前输出与存储在文件中的输出进行比较。如果没有,那么就不要比较,只打印最近的数字。
这是我的脚本;
#!/bin/bash
warning="\e[93m%-17s%-12s%-12s\n"
danger="\e[91m%-17s%-12s%-12s\n"
green="\e[92m%-17s%-12s%-12s\n"
normal="%-17s%-12s%-12s\n"
wallets=/usr/local/bin/*-cli
current_date=$(date +%s)
for i in $wallets; do
current_blocks=`$i getblockcount`
coin_name=`basename $i -cli`
if [ ! "$line" ]; then
read line
set -- $line
fi
if [ "$1" == "$coin_name" ]; then
line='' # read new line next time
time_difference=$(( $current_date - $3 ))
if (( time_difference > 3600 )); then
if (( current_blocks > $2 )); then
printf "$green" $coin_name $current_blocks $2
sed -i '' "/$1/c$1 $current_blocks $current_date" blocks.log
tput sgr0
else
printf "$danger" $coin_name $current_blocks $2
sleep 2
tput sgr0
fi
elif (( time_difference > 1800 )); then
if (( current_blocks > $2 )); then
printf "$green" $coin_name $current_blocks $2
sed -i '' "/$1/c$1 $current_blocks $current_date" blocks.log
tput sgr0
else
printf "$warning" $coin_name $current_blocks $2
sleep 2
tput sgr0
fi
else
printf "$normal" $coin_name $current_blocks $2
tput sgr0
fi
else
# $line as well as $1 and $2 remain set, will be used in next loop cycle
if [ ! "$1" ]; then # $1 is empty at EOF
# create a new blocks.log to not disturb reading from original:
cp blocks.log $$; mv $$ blocks.log
echo "$coin_name $current_blocks $current_date" >>blocks.log
else
# insert before current line (address /$1/)
sed -i '' "/$1/i$coin_name $current_blocks $current_date" blocks.log
fi
fi
done <blocks.log
这是blocks.log 文件的示例输出;
# first one is the $coin_name second one is $current_blocks and the third one is unix time.
bitcoin 99983 1550742031
litecoin 138432 1550742031
dash 130994 1550742031
当您运行脚本时,它会显示与blocks.log 文件类似的输出,并根据脚本中的if-else 条件在blocks.log 文件中修改它们。
问题
这个脚本的问题是,当我最初运行它几次时,它工作得很好,几乎可以立即循环,但是随着我越来越多地运行脚本或者只是运行它几次然后等待大约 5-6 小时,然后再次运行脚本,它需要几乎几个小时来循环,考虑到只有几个 $wallets 并且当您运行 $i getblockcount 命令时它们会立即为您提供输出,这应该是即时的所以我不知道为什么一段时间后运行脚本需要几个小时。
我该如何解决这个问题?
【问题讨论】:
-
你正在同时读取和写入文件
blocks.log- 这不健康。不确定这是否是问题,但你应该明确地解决它。您可能还想看看shellcheck.net。 -
谢谢,我去看看。我不知道如何以其他方式而不是同时阅读和写作。
-
1.计算新值并将它们写入变量或临时文件。 2. 最后用新文件覆盖旧文件。
-
@Socowi 你介意用示例脚本回答这个问题吗?对不起,我是 bash 的新手,所以..
-
@Armali 看起来它没有挂起。我发现脚本正在退出,因为在某些情况下,
$2s 之一被删除。它只是随机删除,所以我猜是因为同时读/写而发生了冲突。
标签: bash