Bash How to Sum Variables
Let’s define two variables:
FILES_ETC=1416 FILES_VAR=7928
If you want to get total value, you can do:
TOTAL_FILES=$((FILES_ETC+FILES_VAR)) echo $TOTAL_FILES
For 100% compatibility with old shells, you can use external command expr. In modern systems (ec. Centos 7 64bit), in fact, expr is not an external command. It is an internal shell function. So there is not a significant difference in speed between the above and this command:
TOTAL_FILES=`expr $FILES_ETC + $FILES_VAR` echo $TOTAL_FILES
Funny thing is that there must be spaces between arguments. In fact, expr is a command, $FILES_ETC is the first argument, + is the second argument and $FILE_VAR is the third argument.
If you want to add numbers with decimal points, you can use bc. bc is a very useful external command for making arithmetical operations:
TOTAL_FILES=$(echo $FILES_ETC + $FILES_VAR | bc) echo $TOTAL_FILES
Common mistakes are spaces before or after ‘=’ sign. However bc and expr commands expect spaces between arguments and operators, so in these cases don’t forget to spaces.