BASH比較文字列/整数エラー

BASH比較文字列/整数エラー

価格を確認するためにこのスクリプトを作成しています。 16行目に達するとエラーが発生します。

#!/bin/bash

echo "   Date        Time     Price"
echo "-----------------------------"
while [ true ]
do

new_price=$(curl -s "https://coinbase.com/api/v1/prices/spot_rate" | jq -r ".amount")

balance=0.000001

if [ -z $current_price ]; then
current_price=0
fi

if [ $current_price < $new_price ]; then
ARROW="+"
else if [ $current_price > $new_price ]; then
ARROW="-"
else
ARROW="="
fi
fi

echo "$(date '+%m/%d/%Y | %H:%M:%S') | $new_price | $ARROW"

current_price=$new_price
sleep 30
done

出力エラー

-PC:~/scripts/ticker$ ./arrows.sh
   Date        Time     Price
-----------------------------
./arrows.sh: line 16: 7685.00: No such file or directory
11/17/2017 | 15:45:28 | 7685.00 | -

これは詳細です

-PC:~/scripts/ticker$ bash -x ./arrows.sh
+ echo '   Date        Time     Price'
   Date        Time     Price
+ echo -----------------------------
-----------------------------
+ '[' true ']'
++ curl -s https://coinbase.com/api/v1/prices/spot_rate
++ jq -r .amount
+ new_price=7685.00
+ balance=0.000001
+ '[' -z ']'
+ current_price=0
+ '[' 0 ']'
+ ARROW=+
++ date '+%m/%d/%Y | %H:%M:%S'

ベストアンサー1

変える:

if [ $current_price < $new_price ]; then
ARROW="+"
else if [ $current_price > $new_price ]; then
ARROW="-"
else
ARROW="="
fi
fi

そして:

if echo "$current_price < $new_price" | bc | grep -q 1; then
    ARROW="+" 
elif  echo "$current_price > $new_price" | bc | grep -q 1; then
    ARROW="-"
else
    ARROW="="
fi

test([)の数値より小さい比較演算子-ltではありません<。 (これは<入力リダイレクトのためのものです。)したがって、価格が整数の場合は、次のものを使用できます。

if [ "$current_price" -lt "$new_price" ]; then

ただし、価格は浮動小数点であるため、bc計算を実行するには同等の方法が必要です。論理条件が真か偽かをbc出力します。私たちはそれに応じて使用できる正しい戻りコードを設定します。10grep -q 1if

また、bashのサポートelifelse ifif-then-else-fi

おすすめ記事