Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For reference, here are something resembling the "usual" ideal answers to this.</p> <pre><code>#!/usr/bin/env bash # Bash/ksh93 # Theoretically also zsh/mksh, but both have bugs that break it. function fib1 { # It is critical to validate user input if it will be used in an arithmetic # expression. [[ $1 == +([[:digit:]]) ]] || return 1 # Demonstrates an accumulating version to print the intermediary results. typeset i=1 f=(0 1) while (( i &lt; $1 )); do # Don't use expr(1) unless you're coding for Bourne. (( f[i] = f[i-1] + f[i++] )) done echo "${f[@]}" } fib1 "$1" </code></pre> <p>It is confusing that in addition to the broken syntax, you're using strange <code>expr</code> even with a <code>/bin/bash</code> shebang. You should read the bash manual and not read whatever suggested that to you.</p> <pre><code>#!/bin/sh # POSIX (posh/bash/zsh/all kshes) # It's easier to write a let wrapper than re-type test expressions repeatedly. # This emulates let precisely, but it's not important to understand everything # going on here. Breaks in dash because of its lack of support for the # otherwise ubiquitously supported comma operator, and busybox because of a bug in # its environment assignments. let() { IFS=, command eval test '$(($*))' -ne 0 } fib2() { # Uglier validation for POSIX case $1 in *[^[:digit:]]*|'') return 1 esac # Using globals for simplicity count=$1 n1=0 n2=1 while let count-=1; do let n1=n2 n2=${n1}+n2 done printf 'Fib Num: %d\n' "$n2" } fib2 "$1" </code></pre> <p>My arithmetic fibonacci is somewhat popular as a curiosity.</p> <pre><code># Bash/ksh93/zsh # Could be more elegant but includes bug workarounds for ksh/zsh $ a=a[++n%20]=a[n]+a[n-1],a[0] a[n=2]=1; let a a=0; echo "${a[@]}" 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 # Less portable because of bugs. Works in Bash. $ a=('a[a[n]=a[n-1]+a[n-2],n++/20]' 2 0 1); echo "${a[@]:n=4,a}" 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload