since2012/04/23

     
 
最近升级日期:2009/02/18

大标题的图示重点回顾
  • shell script 是利用 shell 的功能所写的一个『程序 (program)』,这个程序是使用纯文字档,将一些 shell 的语法与命令(含外部命令)写在里面, 搭配正规表示法、管线命令与数据流重导向等功能,以达到我们所想要的处理目的
  • shell script 用在系统管理上面是很好的一项工具,但是用在处理大量数值运算上, 就不够好了,因为 Shell scripts 的速度较慢,且使用的 CPU 资源较多,造成主机资源的分配不良。
  • 在 Shell script 的文件中,命令的运行是从上而下、从左而右的分析与运行;
  • shell script 的运行,至少需要有 r 的权限,若需要直接命令下达,则需要拥有 r 与 x 的权限;
  • 良好的程序撰写习惯中,第一行要宣告 shell (#!/bin/bash) ,第二行以后则宣告程序用途、版本、作者等
  • 对谈式脚本可用 read 命令达成;
  • 要创建每次运行脚本都有不同结果的数据,可使用 date 命令利用日期达成;
  • script 的运行若以 source 来运行时,代表在父程序的 bash 内运行之意!
  • 若需要进行判断式,可使用 test 或中括号 ( [] ) 来处理;
  • 在 script 内,$0, $1, $2..., $@ 是有特殊意义的!
  • 条件判断式可使用 if...then 来判断,若是固定变量内容的情况下,可使用 case $var in ... esac 来处理
  • 回圈主要分为不定回圈 (while, until) 以及固定回圈 (for) ,配合 do, done 来达成所需任务!
  • 我们可使用 sh -x script.sh 来进行程序的 debug

大标题的图示本章习题
( 要看答案请将鼠标移动到『答:』底下的空白处,按下左键圈选空白处即可察看 )
底下皆为实作题,请自行撰写出程序喔!
  • 请创建一支 script ,当你运行该 script 的时候,该 script 可以显示: 1. 你目前的身份 (用 whoami ) 2. 你目前所在的目录 (用 pwd)
    #!/bin/bash
    echo -e "Your name is ==> $(whoami)"
    echo -e "The current directory is ==> $(pwd)"
  • 请自行创建一支程序,该程序可以用来计算『你还有几天可以过生日』啊?
    #!/bin/bash
    read -p "Pleas input your birthday (MMDD, ex> 0709): " bir
    now=`date +%m%d`
    if [ "$bir" == "$now" ]; then
    echo "Happy Birthday to you!!!"
    elif [ "$bir" -gt "$now" ]; then
    year=`date +%Y`
    total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))
    echo "Your birthday will be $total_d later"
    else
    year=$((`date +%Y`+1))
    total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24))
    echo "Your birthday will be $total_d later"
    fi
  • 让使用者输入一个数字,程序可以由 1+2+3... 一直累加到使用者输入的数字为止。
    #!/bin/bash
    read -p "Please input an integer number: " number
    i=0
    s=0
    while [ "$i" != "$number" ]
    do
    i=$(($i+1))
    s=$(($s+$i))
    done
    echo "the result of '1+2+3+...$number' is ==> $s"
  • 撰写一支程序,他的作用是: 1.) 先查看一下 /root/test/logical 这个名称是否存在; 2.) 若不存在,则创建一个文件,使用 touch 来创建,创建完成后离开; 3.) 如果存在的话,判断该名称是否为文件,若为文件则将之删除后创建一个目录,档名为 logical ,之后离开; 4.) 如果存在的话,而且该名称为目录,则移除此目录!
    #!/bin/bash
    if [ ! -e logical ]; then
    touch logical
    echo "Just make a file logical"
    exit 1
    elif [ -e logical ] && [ -f logical ]; then
    rm logical
    mkdir logical
    echo "remove file ==> logical"
    echo "and make directory logical"
    exit 1
    elif [ -e logical ] && [ -d logical ]; then
    rm -rf logical
    echo "remove directory ==> logical"
    exit 1
    else
    echo "Does here have anything?"
    fi
  • 我们知道 /etc/passwd 里面以 : 来分隔,第一栏为帐号名称。请写一只程序,可以将 /etc/passwd 的第一栏取出,而且每一栏都以一行字串『The 1 account is "root" 』来显示,那个 1 表示行数。
    #!/bin/bash
    accounts=`cat /etc/passwd | cut -d':' -f1`
    for account in $accounts
    do
    declare -i i=$i+1
    echo "The $i account is \"$account\" "
    done

大标题的图示参考数据与延伸阅读

 
     
http://linux.vbird.org is designed by VBird during 2001-2011. ksu.edu 

本网页主要以Firefox配合解析度 1024x768 作为设计依据     鸟哥自由软件整合应用研究室