检查 $((a * b)) 在我自己的 shell 中计算

检查 $((a * b)) 在我自己的 shell 中计算

POSIX 似乎定义 shell 应该能够像计算器一样计算表达式$(( a * b))where*是二元运算符 +、- 或 *。我为自己的 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

答案1

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

这应该有效;如果您的 shell 不使用$(( ))算术运算,则字符串将不匹配。您还可以将其简写为:

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

相关内容