0

is it possible to assign the value of a call to a recursive script, to a variable? Here is my code, the error says that on line 10: RIS = 2*1... 3*2 etc That seems good work, but RIS is not assigned to a real value.

DECR=$1

if [[ ${DECR} -gt 0 ]] ; then
    echo ${DECR}
    ((DECR2 = ${DECR}-1))
    ((RIS = ${DECR} * `./fattoriale1.sh ${DECR2}`))
else
    ((RIS=1))
fi

echo ${RIS}

Error: ./fattoriale1.sh: riga 9: ((: RIS = 2 * 1
1: errore di sintassi nell'espressione (il token dell'errore è "1")
./fattoriale1.sh: riga 9: ((: RIS = 3 * 2
2: errore di sintassi nell'espressione (il token dell'errore è "2")
./fattoriale1.sh: riga 9: ((: RIS = 4 * 3
6: errore di sintassi nell'espressione (il token dell'errore è "6")
12

Thanks.

2
  • 2
    @123, not so. This is perfectly legal: echo $(( `echo 42` - `false; echo $?` )) Commented Feb 4, 2016 at 11:23
  • @glennjackman That isn't (()) it's $(()). Actually looks like both can. My bad. Commented Feb 4, 2016 at 11:27

1 Answer 1

1

You have 2 echo statements in your function, so if DECR > 0 then the output of the function contains a newline. The error message indicates you're trying to execute:

((RIS = 2 * 1
1))

Remove echo $DECR or change it to print to stderr: echo $DECR >&2

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works. I really didn't know how to do, that echo was only a check output. Another question: is there a way to write the same scipt using only one DECR variable instead of two?
yes: factorial () { local n=$1; [[ $n -eq 1 ]] && echo 1 || echo $(( n * $( factorial $((n-1)) ) )); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.