s3a
March 8th, 2017, 12:49 AM
Hello, fellow Linux lovers. :)
I'm trying to write the BASH equivalent of the following Java syntax.:
public int factorial(int n) {
if(n>1) {
return n * factorial(n-1);
} else {
return 1;
}
}
int result = factorial(5);
System.out.println(result);
This works (and prints out 120, as intended).:
#!/bin/bash
function f() {
n=$1;
if [[ n -gt 1 ]]; then
echo $(($n*$(f $(($n-1)) )));
else
echo 1;
fi
}
f 5;
This does not work.:
#!/bin/bash
result=-1;
function f() {
n=$1;
if [[ n -gt 1 ]]; then
result=$(($n*$(f $(($n-1)) )));
else
result=1;
fi
}
f 5;
echo $result;
The error it gives is as follows.:
./script
./script: line 9: 2*: syntax error: operand expected (error token is "*")
./script: line 9: 3*: syntax error: operand expected (error token is "*")
./script: line 9: 4*: syntax error: operand expected (error token is "*")
./script: line 9: 5*: syntax error: operand expected (error token is "*")
-1
Could someone please help me find the BASH-equivalent of the Java syntax above?
Any help in getting me to achieve with BASH what the Java syntax above shows would be GREATLY appreciated!
I'm trying to write the BASH equivalent of the following Java syntax.:
public int factorial(int n) {
if(n>1) {
return n * factorial(n-1);
} else {
return 1;
}
}
int result = factorial(5);
System.out.println(result);
This works (and prints out 120, as intended).:
#!/bin/bash
function f() {
n=$1;
if [[ n -gt 1 ]]; then
echo $(($n*$(f $(($n-1)) )));
else
echo 1;
fi
}
f 5;
This does not work.:
#!/bin/bash
result=-1;
function f() {
n=$1;
if [[ n -gt 1 ]]; then
result=$(($n*$(f $(($n-1)) )));
else
result=1;
fi
}
f 5;
echo $result;
The error it gives is as follows.:
./script
./script: line 9: 2*: syntax error: operand expected (error token is "*")
./script: line 9: 3*: syntax error: operand expected (error token is "*")
./script: line 9: 4*: syntax error: operand expected (error token is "*")
./script: line 9: 5*: syntax error: operand expected (error token is "*")
-1
Could someone please help me find the BASH-equivalent of the Java syntax above?
Any help in getting me to achieve with BASH what the Java syntax above shows would be GREATLY appreciated!