作爲參考,這裏有一些類似於「常見」的理想答案。
#!/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 < $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"
這是令人困惑的是,除了破碎的語法,你用奇怪expr
即使有/bin/bash
家當。你應該閱讀bash手冊,而不是閱讀給你的任何建議。
#!/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"
我的算術斐波那契有點好奇。
# 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
這是令人沮喪的..即時通訊「行10:[:2:一元操作符預計」現在 – user2012751 2013-03-05 22:51:51
你如何運行腳本? – 2013-03-05 22:53:24
@ user2012751:嘗試在'$ count'和'-le'和'$ 1'之間移除while條件中的空格:'while [$ count-le $ 1]'。它現在工作嗎? – 2013-03-05 22:54:49