1、扫描/etc/passwd文件每一行,如发现GECOS字段为空,则填 充用户名和单位电话为62985600,并提示该用户的GECOS信 息修改成功。

#!/bin/bash
while read line ;do
if  echo "$line" | cut -d: -f5 | grep "^$" &> /dev/null ;then
        name=`echo "$line" | cut -d: -f1`
        chfn -f $name $name &> /dev/null
        chfn -p "62985600" $name &> /dev/null
        echo "Add GECOS for `$name` successfully"
fi
done < /etc/passwd

2、写一个函数实现两个数字做为参数,返回最大值

先写一个函数

#!/bin/bash
#find the biger number
max(){
if [  $1 -ge $2 ];then
        max=$1
else
        max=$2
fi
echo "$max"
}

再在脚本中调用

#!/bin/bash
. maxfun
max $1 $2

执行结果

[root@shao testdir]# bash max.sh 4 7
7

3、写一个函数实现数字的加减乘除运算,例如输入 1 + 2,,将得出正 确结果

#!/bin/bash
#
calculator(){
echo $@ | bc
}
calculator $@

运行结果

[root@shao testdir]# bash jisuan.sh 3*8
24
[root@shao testdir]# bash jisuan.sh 4/2
2
[root@shao testdir]# bash jisuan.sh 4+2
6

4、斐波那契数列又称黄金分割数列,因数学家列昂纳多·斐波那契以兔子 繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:0、1 、1、2、3、5、8、13、21、34、……,斐波纳契数列以如下被以递归的 方法定义:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2) 写一个函数,求n阶斐波那契数列

#!/bin/bash
#Author:liushaoshao
#time:2016-08-19 22:43:57
#version:1.0
#description:Fibonacci sequence
fib(){
        if [ $1 -eq 0 ];then
                echo "0"
        elif [ $1 -eq 1 -o $1 -eq 2 ];then
                echo "1"
        else
                echo  "$[$(fib $[$1-1])+$(fib $[$1-2])]"
        fi
}
read -p "Please input the xiangshu(0,1,2...):" xs
if expr $xs + 1 &> /dev/null ;then
        for ((i=0;i<=xs;i++));do
                fib $i
        done
else
        echo "only int number(0,1,2...) allowed"
        exit 100
fi

运行结果

[root@shao testdir]# bash feib.sh 
Please input the xiangshu(0,1,2...):-1
only int number(0,1,2...) allowed
[root@shao testdir]# bash feib.sh 
Please input the xiangshu(0,1,2...):5
0
1
1
2
3
5

5、汉诺塔(又称河内塔)问题是源于印度一个古老传说。大梵天创造世 界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着 64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放 在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间 一次只能移动一个圆盘。 利用函数,实现N片盘的汉诺塔的移动步骤

#!/bin/bash  
  
move=0  
  
dohanoi()   
{  
    if [ $1 -eq 0 ]  
    then  
       echo ""   
    else  
        dohanoi "$(($1-1))" $2 $4 $3  
        echo "move $2 ----> $3"  
          
        let "move=move+1"  
  
        dohanoi "$(($1-1))" $4 $3 $2  
    fi  
      
    if [ $# -eq 1 ]  
    then  
        if [ "$(( $1 > 1 ))" -eq 1 ]  
        then  
            dohanoi $1 A C B  
            echo "Total moves  = $move"  
        else  
           echo "The number of disk which you input is illegal! "  
         fi  
    fi  
}  
  
echo "Please input the num of disk:"  
read num  
dohanoi $num 'A' 'B' 'C'