0

I need to do some calculations in a "#!/bin/bash" shell script, but I cannot seem to get the syntax right. In PHP, I would have written:

$zosx = ( $x + round( $w * 0.25 ) );
$zosy = ( $y + round( $h * 0.75 ) );
$zoex = ( $x + round( $w * 0.5 ) );
$zoey = ( $y + round( $h / 2 ) );

May I ask someone to give me the right syntax for a shell script?

For context, what comes before these math calculations is:

unset x y w h
  eval $(xwininfo -id $(xdotool getactivewindow) |
    sed -n -e "s/^ \+Absolute upper-left X: \+\([0-9]\+\).*/x=\1/p" \
           -e "s/^ \+Absolute upper-left Y: \+\([0-9]\+\).*/y=\1/p" \
           -e "s/^ \+Width: \+\([0-9]\+\).*/w=\1/p" \
           -e "s/^ \+Height: \+\([0-9]\+\).*/h=\1/p" )

This is running on a typical Debian 11 system.

Eriks
  • 41
  • 2
  • Do you use `sh` or `bash`? – Cyrus Apr 02 '22 at 19:25
  • I used #!/bin/sh, but I will switch to #!/bin/bash. Sorry, my age is showing. – Eriks Apr 02 '22 at 19:28
  • 1
    `sh` nor `bash` can't do floating point calculations. You can as well call `php` from your bash script to do the math. https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks https://stackoverflow.com/questions/14222250/floating-point-arithmetic-in-unix-shell-script https://unix.stackexchange.com/questions/412716/can-bash-do-floating-point-arithmetic-without-using-an-external-command – KamilCuk Apr 02 '22 at 19:31
  • Do consider parsing the output of `xwininfo` in native bash instead of doing hackery with `eval`. A string that doesn't match any of your sed expressions getting evaluated as code could be bad. [BashFAQ #1](https://mywiki.wooledge.org/BashFAQ/001) talks about some of the basics of reading data into bash; [BashFAQ #100](https://mywiki.wooledge.org/BashFAQ/100) goes into detail on what the available string manipulation primitives are -- which includes native (no-`sed`-needed) regex support. – Charles Duffy Apr 02 '22 at 19:44
  • So, the answer is to use: `let "zosx = ( x + ( w / 4 ))" let "zosy = ( y + ( h / 4 * 3 ))" let "zoex = ( x + ( w / 2 ))" let "zoey = ( y + ( h / 2 ))"` – Eriks Apr 02 '22 at 20:04
  • If all four variables contain integers and the result should also be integer, then you can use that too with `bash`, e.g.: `zosy=$((y+h/4*3))` – Cyrus Apr 02 '22 at 21:06

0 Answers0