Recursive function in bash

There are several syntax and a quite obvious logic one (return 0)

A working version is below:

#!/bin/bash

factorial()
{
    if (( $1 <= 1 )); then
        echo 1
    else
        last=$(factorial $(( $1 - 1 )))
        echo $(( $1 * last ))
    fi
}
factorial 5

You are missing:

  1. return is bad (should use echo)

  2. shbang line (is /bin/bash not /bash/bin)

  3. Can’t do arithmetic outside of (( )) or $(( )) (or let, but (( )) is preferred)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)