Skip to content

Instantly share code, notes, and snippets.

@VonC
Last active July 22, 2023 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VonC/59cb248356a85b3b193f9258df474015 to your computer and use it in GitHub Desktop.
Save VonC/59cb248356a85b3b193f9258df474015 to your computer and use it in GitHub Desktop.
Sum with bash

If you are working in a bash-like environment such as Git Bash on Windows, you can use the built-in shell arithmetic expansion feature for calculating sums. That feature allows you to perform arithmetic operations within your shell script without using any external commands like bc.

A script like:

#!/bin/bash
# read each line from the file
while read line; do
  # evaluate the arithmetic expression in the line
  result=$((line))
  # print the result
  echo $result
done < yourfile.txt

Replace yourfile.txt with the name of your file. Each line in your file should contain an arithmetic expression, like 2 + 2 or 3 * 7. The script will calculate the result of each expression and print it.

Warning: bash only supports integer arithmetic, so if you need to perform operations with floating point numbers, you will have to use a different approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment