Subtracting strings (numbers) in a shell script

I made a shell script that finds the size of the directory, returning it to a human readable format (e.g. 802M or 702K). I want to calculate the difference between the sizes.

Here is my shell script:

#!/bin/bash

current_remote_dir_size=789M
new_remote_dir_size=802M
new_size=`echo ${new_remote_dir_size} | grep -o [0-9]*`
current_size=`echo ${current_remote_dir_size} | grep -o [0-9]*`

echo "${new_size}-${current_size}"

But script output is just

-

How can I do a subtraction?

+5
source share
3 answers

You can do basic math with an integer in bash by wrapping the expression in $((and )).

$ echo $(( 5 + 8 ))
13

In your specific case, the following works for me:

$ echo "${new_size}-${current_size}"
802-789
$ echo $(( ${new_size}-${current_size} ))
13

Your end result is a bit strange. Make sure that the grep expression really gives the desired result. If not, you may need to wrap the regular expression in quotation marks.

+11
source

grep, :

current_remote_dir_size=789M
current_size=${current_remote_dir_size%[A-Z]}
echo $current_size  # ==> 789

new_remote_dir_size=802M
new_size=${new_remote_dir_size%[A-Z]}
echo $new_size      # ==> 802

. bash.

+1

, , :

echo $((${new_remote_dir_size/M/}-${current_remote_dir_size/M/}))
  • $ ((a + b - 4)) can be used for arithmetic expressions
  • $ {string / M /} replaces M in the string with nothing. See man bashString Substitution for more features and details.
+1
source

All Articles