3

I am having trouble with what should be a simple bash script.

I have a bash script that works perfectly:

function convert_to ()

x_max=2038
y_max=1146
x_marg=100
y_marg=30
x_grid=150
y_grid=150

if (("$x_pos" > "($x_marg+($x_grid/2))")); then
    x_pos=$((x_pos-x_marg))
    x_mod=$((x_pos%x_grid))
    x_pos=$((x_pos/x_grid))
    x_pos=$((x_pos*x_grid))
fi

However, I want to change the script where I pass 4 values to the function as arguments:

function convert_to ()

pos="$1"
marg="$2"
grid="$3"
max="$4"

# I verify that the inputs have arrived with this display 
zenity --info --title "Info" --text "inputs: pos: $pos marg: $marg grid: $grid max: $max"

if (("$pos" > "($marg+($grid/2))")); then
    pos=$((pos-marg))
    mod=$((pos%grid))
    pos=$((pos/grid))
    pos=$((pos*grid))
fi
}

Where I would then call the function as follows:

x_pos="$(convert_coordinates $x_pos, $x_marg, $x_grid, $x_max)"
Y_pos="$(convert_coordinates $y_pos, $y_marg, $y_grid, $y_max)"

However, the new script always fails with syntax errors: operand expected (error token is ",").

I've also tried many variations:

pos=$[[ $pos - $marg ]] ...... which results in syntax error: operand expected (error token is "[ 142, - 100, ]")
pos=[[ $pos - $marg ]] .......... fails with command not found
pos=$[[ "$pos" - "$marg" ]] ..... fails with command not found
pos=$(("$pos"-"$marg")) ......... syntax error: operand expected (error token is ""142,"-"100,"")

The only difference between the working script and non-working is the fact that I am passing the arguments in the second script ... So, i tried setting the argument values to constant values within the function (defeating my purpose of passing arguments and making the script worthless) .. But, now the calculations within the function are working without error.

So I'm at a loss for what I am doing incorrectly ... I want to be able to pass arguments to the function and then do mathematical calculations using the passed values.

5

In , the argument separators are spaces, so :

instead of :

x_pos="$(convert_coordinates $x_pos, $x_marg, $x_grid, $x_max)"

do

x_pos="$(convert_coordinates $x_pos $x_marg $x_grid $x_max)"
  • I've been staring at this code all day ... and didn't see that .... It is now working ... Actually the error code kept showing an extra comma ... and I didn't understand where it was coming from. thanks – daniel Sep 9 '15 at 19:40
  • @daniel if this answer solved the problem, you should click the check mark to accept it – Eric Renouf Sep 9 '15 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.