Recursive function in bash

后端 未结 6 1648
渐次进展
渐次进展 2020-12-13 09:33

I want to do a function that will return the factorial of a number in bash

Here\'s the current code that doesn\'t work, can anyone tell me what\'s wrong and how to c

6条回答
  •  感情败类
    2020-12-13 10:26

    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)

提交回复
热议问题