4

I have this script that is to rescale images to a percentage value

#!/bin/bash

percent=$1
echo $percent


for img in `find *.png`;
do
  echo Processing file $img
  width=$( mdls $img  | grep kMDItemPixelWidth | tail -n1 | cut -d= -f2 )
  height=$( mdls $img | grep kMDItemPixelHeight | tail -n1 | cut -d= -f2 )

  newWidth=$((width*percent))
  newHeight=$((height*percent))
  echo $newWidth $newHeight
  sips -z $newWidth $newHeight $img
done

My bash is configured to accept commas as decimal separators.

So, whey I type

rescale 0,3019

I am trying to rescale the images to 30.19% of their values

the problem is that the line

  echo $newWidth $newHeight

shows me the values as they were multiplied by 3019. Strangely the first echo

echo $percent

shows me 0,3019 (the correct value)

what am I missing?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Duck
  • 4,434
  • 19
  • 51
  • 64
  • Try Dividing percent by 100 and then adding 1, after accepting 30.19 as the input. You'd end up at Cyrus's answer, ie, a decimal is not an integer – eyoung100 Oct 03 '14 at 20:59
  • 2
    What do you mean by "My bash is configured to accept commas as decimal separators."? This is surprising because bash doesn't have such a notion (it can't handle non-integer numbers). – vinc17 Oct 03 '14 at 21:15
  • `awk` is available on nearly any system that has `bash grep cut` and can do the text selections and floating-point in one command: `mdls $img | awk -F= -vf=$img -vp=,33 '/kMDItemPixelHeight{h=$2*p}/kMDItemPixelWidth{w=$2*p} END{system("sips -z " w " " h " " f)}'` (plus minor tweaks for decimal-comma if your locale doesn't handle it, or if $img contains special chars). – dave_thompson_085 Oct 04 '14 at 07:24

1 Answers1

6

To your headline: bash can only multiply integers.

Cyrus
  • 12,059
  • 3
  • 29
  • 53
  • what???? so, what is the best solution for that? – Duck Oct 03 '14 at 20:40
  • 1
    You can use `bc`: `echo 0.3333*17.2 | bc` or write a function to do the job. As example: integer division with floating point results: http://stackoverflow.com/a/24431665/3776858 – Cyrus Oct 03 '14 at 20:44
  • 2
    or a little shorter `bc<<<0.3333*17.2` – phil294 Feb 20 '18 at 03:05