存储循环中的值并在每次运行脚本时比较它们

存储循环中的值并在每次运行脚本时比较它们

描述

你好,

我试图循环某些命令并将其输出保存到文件中,在循环这些命令时,还要检查我们保存其输出的文件,以便我们可以在循环命令的同时从文件中比较它们。最后,检查循环命令的输出是否与该文件中先前保存的输出匹配。(还要检查文件是否不包含输出并将其添加到文件中,以便我们稍后可以使用它再次进行比较)

这是我的主脚本,它循环遍历位于内部的上述命令,/usr/local/bin/以便我可以直接从 shell 运行它们。

#!/bin/bash
wallets=`find /usr/local/bin/ -iname '*-cli'`

for i in $wallets; do
    current_blocks=`$I getblockcount`
    coin_name=${i:15:-4} # I use `:15:-4` here to cut the path and the last 4 characters. (For example it's `/usr/local/bin/bitcoin-cli` so I change it to `bitcoin` only
    echo $coin_name $current_blocks
    echo $coin_name $current_blocks >> blocks.log
done

这个 echo 给了我们准确的结果(假设 ; 中有 2 个项目$wallets

bitcoin 1457824
litecoin 759345

这就是我将使用的 while 循环 - 大概 - 从文件中读取;

while read line ; do
    set $line
    echo $1 $2
done < blocks.log

当我们运行它时,它也会给我们这个输出;

bitcoin 1457824
litecoin 759345

因此,由于我有这两个代码位,现在我想将它们合并到一个脚本中,这样我既可以使用第一个代码位来循环命令,也可以将它们与文件进行比较blocks.log(同样,还要检查文件是否不包含输出并将其添加到文件中,以便我们稍后可以使用它再次进行比较)

我的第一个(也是失败的)方法;

for i in $wallets; do

    current_blocks=`$i getblockcount`
    coin_name=${i:15:-4}

    while read line; do
        set $line
        if [ "$1" == "$coin_name" ]; then
            echo "File contains the coin_name, compare the blocks now"
            if (( "$current_blocks" >= "$2" )); then
                echo "Current blocks are greater than the saved blocks"
                echo "Saving the new blocks count now"
                sed -i "s/$1/$1 $current_blocks/" blocks.log
            else
                echo "Current blocks are less than or equals to saved blocks"
            fi
        else
            echo "File does not contain the coin_name, adding it now"
            echo "$coin_name $current_blocks" >> blocks.log
        fi
    done < blocks.log

done

我的第二次(又一次失败)尝试;

for i in $wallets; do

    current_blocks=`$i getblockcount`
    coin_name=${i:15:-4}

    read line < blocks.log
    set $line
    if [ "$1" == "$coin_name" ]; then
        echo "File contains the coin_name, compare the blocks now"
        if (( "$current_blocks" >= "$2" )); then
            echo "Current blocks are greater than the saved blocks"
            echo "Saving the new blocks count now"
            # sed -i "s/$1/$1 $current_blocks/" blocks.log
        else
            echo "Current blocks are less than or equals to saved blocks"
        fi
    else
        echo "File does not contain the coin_name, adding it now"
        echo "$coin_name $current_blocks" >> blocks.log
    fi

done

我究竟做错了什么?

相关内容