私のシェルで$((a * b))評価を確認する[閉じる]

私のシェルで$((a * b))評価を確認する[閉じる]

POSIXは、シェルが二項演算子+、-、または*を持つ計算機$(( a * b))などの式を評価できる必要があると定義しているようです。*私は自分のシェルのための電卓を書いて​​、それのためのテストスクリプトを書いた。

$ $((32 * 32))
$((32 * 32))
Result = 1024

ただし、テストを実行すると、シェルから出力(1024)を取得できなくなります。手動でチェックするのではなく、シェルが実際に正しい結果を計算するかどうかをスクリプトでテストしたいと思います。現在、私のテストは手動チェックとして機能しますが、結果が正しいことをプログラムで確認したいと思います。

printf "********************* TEST Arithmetics  ... .\nYou should see the number 4096 below "
#read _
valgrind --leak-check=yes ./shell .<< EOF
echo $((64 * 64))
EOF

テスト結果は次のとおりです。

********************* TEST Arithmetics  ... .
You should see the number 4096 below 'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin.
stdin is a file or a pipe

4096
==31803== 
==31803== HEAP SUMMARY:
==31803==     in use at exit: 79,725 bytes in 167 blocks
==31803==   total heap usage: 502 allocs, 335 frees, 228,175 bytes allocated
==31803== 
==31803== LEAK SUMMARY:
==31803==    definitely lost: 0 bytes in 0 blocks
==31803==    indirectly lost: 0 bytes in 0 blocks
==31803==      possibly lost: 0 bytes in 0 blocks
==31803==    still reachable: 79,725 bytes in 167 blocks
==31803==         suppressed: 0 bytes in 0 blocks
==31803== Reachable blocks (those to which a pointer was found) are not shown.
==31803== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==31803== 
==31803== For counts of detected and suppressed errors, rerun with: -v
==31803== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)
==31805== Memcheck, a memory error detector
==31805== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==31805== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==31805== Command: ./shell .
==31805== 

修正する

これは動作し、ファイルに書き込み、ファイル内の数字1024を検索します。

#!/bin/ksh
#read _
./shell .<< EOF > tmp.txt
echo $((32*32))
EOF

ベストアンサー1

if [ "1024" == "$((32*32))" ]; then
    echo "The test worked"
else
    echo "The test failed"
fi

これはうまくいきます。シェルが算術を使用しない場合、$(( ))文字列は一致しません。次のように短縮することもできます。

[ "1024" == "$((32*32))" ] || echo "I can't math!"

おすすめ記事