『BASH』——{select、函数与递归}

一、select循环体用法

「select VAR in list; do COMMANDS; done」

select本身是一个死循环,需要设置中断条件;PS3变量是专用于select的提示符

[fh@7 sh]$ cat select.sh 
#!/bin/env bash
animals=(
cat
dog
monkey
tiger
lion
pig
horse
)

echo -e \
"========================================\
\nGuess which animal is my favorite? \
\n========================================"

PS3="Please input the number before your choice: "

select VAR in ${animals[@]}
do
    if [[ $VAR == "cat" ]]
    then
        echo "You are my good friends! "
        break
    else
        echo "Oh, no!"
    fi
done
Select
[fh@7 sh]$ bash select.sh 
========================================
Guess which animal is my favorite? 
========================================
1) cat
2) dog
3) monkey
4) tiger
5) lion
6) pig
7) horse
Please input the number before your choice: 1
You are my good friends! 

二、构显汉诺塔(hanoi)移动轨迹

  方法一:递归

#!/bin/bash
hanoi(){
    if [[ $4 == "1" ]]
    then
        echo "$1 ~> $3"
    else
        hanoi $1 $3 $2 $(($4 - 1))
        hanoi $1 $2 $3 1
        hanoi $2 $1 $3 $(($4 - 1))
    fi
}
read -p 'Please input a positive integer: ' floors
hanoi A B C $floors

  方法二:穷举

#!/bin/bash
fun0(){
    if [[ (${B[-1]} -gt ${A[-1]} || $B == '') && $A != '' ]]
        then
            B=(${B[@]} ${A[-1]})
            unset A[-1]
            echo "A ~> B"
        else
            A=(${A[@]} ${B[-1]})
            unset B[-1]
            echo "B ~> A"
        fi
}
fun1(){
        if [[ (${C[-1]} -gt ${A[-1]} || $C == '') && $A != '' ]]
        then
            C=(${C[@]} ${A[-1]})
            unset A[-1]
            echo "A ~> C"
        else
            A=(${A[@]} ${C[-1]})
            unset C[-1]
            echo "C ~> A"
        fi
}
fun2(){
        if [[ (${B[-1]} -gt ${C[-1]} || $B == '') && $C != '' ]]
        then
            B=(${B[@]} ${C[-1]})
            unset C[-1]
            echo "C ~> B"
        else
            C=(${C[@]} ${B[-1]})
            unset B[-1]
            echo "B ~> C"
        fi
}
read -p "Please input a positive integer: " num
A=($(seq $num -1 1))
B=()
C=()
while [[ ${#C[@]} -lt $num ]]
do
    fun$(($RANDOM % 3)) 2>/dev/null
done
echo "${C[@]}"

  方法三:迭代(!)

三、递归斐波那契数列

#!/bin/env bash
fibo() {
    if [[ $1 -lt 2 ]]
    then
        echo 1
    else
        echo "$[$(fibo $[$1 - 1]) + $(fibo $[$1 - 2])]"
    fi
}

read -p 'A positive integer: ' num

for j in $(seq 0 1 $num)
do
    echo "$(fibo $j)"
done 
posted @ 2012-08-18 21:19  范辉  阅读(273)  评论(0编辑  收藏  举报