Ksh

檢查 $((a * b)) 在我自己的 shell 中進行評估

  • May 7, 2016

POSIX 似乎定義了一個 shell 應該能夠像計算器一樣計算二元運算符 +、- 或 *$(( a * b))的表達式。*我為自己的 shell 編寫了這樣一個計算器,並為它編寫了一個測試腳本。

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

但是當我執行測試時,我無法從 shell 獲取輸出(1024)。我想在腳本中測試 shell 實際計算正確的結果而不是手動檢查。現在我的測試使用手動檢查,但我想以程式方式檢查結果是否正確。

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
if [ "1024" == "$((32*32))" ]; then
   echo "The test worked"
else
   echo "The test failed"
fi

這應該有效;如果您的外殼不$(( ))用於算術,則字元串將不匹配。您也可以使用以下方式對其進行簡寫:

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

引用自:https://unix.stackexchange.com/questions/281660