Subtracting strings (that are numbers) in a shell script Subtracting strings (that are numbers) in a shell script shell shell

Subtracting strings (that are numbers) in a shell script


You can do basic integer math 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 output at the end is a bit odd. Check that the grep expression actually produces the desired output. If not, you might need to wrap the regular expression in quotation marks.


You don't need to call out to grep to strip letters from your strings:

current_remote_dir_size=789Mcurrent_size=${current_remote_dir_size%[A-Z]}echo $current_size  # ==> 789new_remote_dir_size=802Mnew_size=${new_remote_dir_size%[A-Z]}echo $new_size      # ==> 802

See Shell Parameter Expansion in the bash manual.


All you need is:

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 string with nothing. See man bash, Section String substitution, for more possibilities and details.