转载-shell函数应用实例介绍

本文介绍了一个使用Shell脚本实现的简易数据库管理系统。该系统包括添加员工信息、删除信息等功能,并通过循环和条件判断确保数据输入正确。此外,还演示了如何通过内部函数对数据进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://blog.chinaunix.net/u/4206/showart.php?id=654250

代码:
$cat dbfunctions
addon () {                  # 定义函数addon,他的功能是把新的信息加入datafile
    while true
    do
        echo "Adding information "
        echo "Type the full name of employee "
        read name
        echo "Type address for employee "
        read address
        echo "Type start date for employee (4/10/88 ) :"
        read startdate
        echo $name:$address:$startdate
        echo -n "Is this correct? "
        read ans
        case "$ans"  in
        [Yy]*)
            echo "Adding info..."
            echo $name:$address:$startdate>>datafile
            sort -u datafile -o datafile
            echo -n "Do you want to go back to the main menu? "
            read ans
            if [ $ans = Y -o $ans = y ]
            then
                return        # return命令把控制送回函数被调用时所在的调用程序           
      else
                continue        # 把控制返回到while循环顶部
            fi
                ;;
        *)
            echo "Do you want to try again? "
            read answer
            case "$answer" in
                [Yy]*)
                    continue;;
                *)
                    exit;;
            esac
                ;;
        esac
    done
}       # 结束函数定义

$cat mainprog
#!/bin/sh
script. name: mainprog
# This is the main script. that will call the function, addon

#datafile=$HOME/bourne/datafile
datafile=./datafile

.  dbfunctions  # dot命令把文件dbfunctions装入内存,

if [ ! -f $datafile ]
then
    echo "`basename $datafile` does not exist" 1>&2
    exit 1
fi
echo "Select one: "
cat <<EOF
    [1] Add info
    [2] Delete info
    [3] Exit
EOF
read choice
case $choice in
    1)  addon   # 调用函数
        ;;
    2)  delete  # 调用函数
        ;;
    3)  update
        ;;
    4)  echo Bye
        exit 0
        ;;
    *)  echo Bad choice
        exit 2
        ;;
esac
echo Returned from function call
echo The name is $name
# Variable set in the function are known in this shell.

附:文件datafile
cat database
Ann Stephens            111 Main St, Boston, MA         4/10/88
TB Savage               222 B Ave, New York, NY         5/11/99
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值