0

I am very new to Linux shell scripting, and I am trying to write a function to find the distance between two 3D points, $(x_1, y_1, z_1)$ and $(x_2, y_2, z_2)$. This is what I have so far:

Given that the order of parameters is given by $($1, $2, $3, $4, $5, $6) \to (x_1, x_2, y_1, y_2, z_1, z_2)$, my function is

function find_distance() {  
    return $(( sqrt(($2 - $1)^2 + ($4 - $3)^2 + ($6 - $5)^2) ))}

When I ran this function on a set of values and saved it to a variable, like as follows, it returned the error syntax error in expression (error token is "((16.672 - 17.496)^2 + (-2.972 - -3.889)^2 + (9.650 - 9.690)^2)").

My code to try running the function on some values and printing it:

distance_1 = $(find_distance 17.496 16.672 -3.889 -2.972 9.690 9.650)
echo $distance_1

`

How would I fix this? I assume it has something to do with the return value; would I need to define a local variable within the function and return that rather than returning the entire expression?

Thanks.

Alex K
  • 111
  • 2
  • 1
    `$(command)` captures the standard output of the command, not its return value. Use `echo` instead of `return`. – Barmar Jun 16 '23 at 16:34
  • Also, note that bash's built-in math is integer only. The shell has no built-in support for floating-point math at all. – Charles Duffy Jun 16 '23 at 16:37
  • Also, you can't have spaces around the `=` in an assignment outside a math context (yes, you're entering a math context a few characters later, but you aren't in one _yet_). – Charles Duffy Jun 16 '23 at 16:38
  • And this time as a more advisory/stylistic note -- `function funcname() {` merges the legacy ksh syntax `function funcname {` and the POSIX syntax `funcname() {` in a way that's needlessly incompatible with _both_ legacy ksh and POSIX. Don't do that. POSIX has been standardized since the early 1990s; there's no need to merge in legacy throwback syntax from the 80s. – Charles Duffy Jun 16 '23 at 16:38

0 Answers0