기능 매개변수

기능 매개변수

간단한 bash 스크립트를 작성하는 데 문제가 있습니다.

완벽하게 작동하는 bash 스크립트가 있습니다.

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

그러나 4개의 값을 함수에 매개변수로 전달하도록 스크립트를 변경하고 싶습니다.

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
}

그런 다음 다음과 같이 함수를 호출하겠습니다.

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

그러나 새 스크립트는 항상 구문 오류: 피연산자 필요(","로 표시된 오류)로 인해 실패합니다.

나는 또한 다양한 변형을 시도했습니다.

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,"")

작업 스크립트와 작동하지 않는 스크립트의 유일한 차이점은 두 번째 스크립트에서 매개변수를 전달한다는 것입니다... 그래서 매개변수 값을 함수 내부의 상수 값으로 설정해 보았습니다. 스크립트는 쓸모가 없습니다.).. 그러나 이제 함수 내부의 계산이 오류 없이 잘 작동합니다.

그래서 제가 뭘 잘못하고 있는지 알 수 없습니다... 함수에 인수를 전달한 다음 전달된 값을 사용하여 계산을 수행할 수 있기를 원합니다.

답변1

존재하다, 매개변수 구분 기호는 공백이므로 다음과 같습니다.

바꾸다:

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

하다

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

관련 정보