Trying to multiply a float in bash not working

17,980

To your headline: bash can only multiply integers.

Share:
17,980

Related videos on Youtube

Duck
Author by

Duck

Updated on September 18, 2022

Comments

  • Duck
    Duck over 1 year

    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?

    • Admin
      Admin over 9 years
      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
    • Admin
      Admin over 9 years
      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).
    • Admin
      Admin over 9 years
      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).
  • Duck
    Duck over 9 years
    what???? so, what is the best solution for that?
  • phil294
    phil294 about 6 years
    or a little shorter bc<<<0.3333*17.2