Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

六個親手跑過的 Shell 腳本小實例

剛開始學 shell 腳本時,網路上到處是範例,於是乾脆自己一個個敲一遍,收穫確實不小。以下六個小例子都實際跑通過,難度由淺入深。

一、取得本機 IP

#!/bin/bash
a=`ifconfig | grep 'Bcast' | awk {'print $2'} | cut -c 6-`
echo "your PC's IP is "$a

二、用 case 處理 yes/no 輸入

#!/bin/bash
clear
echo -n "enter [y/n]:"
read a
case $a in
    y|Y|Yes|YES|yes) echo "you enter $a";;
    n|N|No|no|No)    echo "you enter $a";;
    *)               echo "error";;
esac

三、讀取檔案的指定行

#!/bin/bash
file="/etc/passwd"
for NUM in 2 4 6 19 13 ; do
    echo `sed -n "$NUM"p $file`
done

四、給函式傳遞參數

#!/bin/bash
# 定義函式
p_num()
{
    num=$1
    echo $num
}
# 用 for 迴圈把每個參數丟進函式
for n in $*
do
    p_num $n
done

五、互動式建立資料夾

#!/bin/bash
while :
do
    echo -n "please input file's name:"
    read a
    if test -e /home/chensiyao/$a
    then
        echo "the file is existing. Please input new file name:"
    else
        mkdir /home/chensiyao/$a
        echo "you are successful!"
        break
    fi
done

六、二進位轉十進位

這個例子把函式、參數解析、字串切片全都用上了,是六個裡最完整的一個。

#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat <<HELP
b2h -- convert binary to decimal
USAGE: b2h [-h] binarynum
OPTIONS: -h help text
EXAMPLE: b2h 111010
will return 58
HELP
exit 0
}

error()
{
    # 印出錯誤訊息並結束
    echo "$1"
    exit 1
}

lastchar()
{
    # 取最後一個字元
    if [ -z "$1" ]; then
        rval=""
        return
    fi
    # 取參數長度,忽略空白
    numofchar=`echo -n "$1" | wc -c | sed 's/ //g'`
    # 取最後一個位元組
    rval=`echo -n "$1" | cut -b $numofchar`
    # 必須是 1 或 0
    if [ "$rval" != "1" -a "$rval" != "0" ]; then
        echo "The number $1 is not a binnum! please check!!!"
        exit 1
    else
        return
    fi
}

chop()
{
    if [ -z "$1" ]; then
        rval=""
        return
    fi
    numofchar=`echo -n "$1" | wc -c | sed 's/ //g'`
    # 長度為 1 時已經沒得砍
    if [ "$numofchar" = "1" ]; then
        rval=""
        return
    fi
    numofcharminus1=`expr $numofchar "-" 1`
    rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`
}

####### 主程式 #######

while [ -n "$1" ]; do
    case $1 in
        -h)  help; shift;;
        --)  shift; break;;
        -*)  error;;
        *)   break;;
    esac
done

# 初始化
sum=0
weight=1

# 沒有參數就印說明
[ -z "$1" ] && help

binnum="$1"
binnumorig="$1"

# 逐位元處理,權重依序為 1, 2, 4, 8 ...
while [ -n "$binnum" ]; do
    lastchar "$binnum"
    if [ "$rval" = "1" ]; then
        sum=`expr "$weight" "+" "$sum"`
    fi
    chop "$binnum"
    binnum="$rval"
    weight=`expr "$weight" "*" 2`
done

echo "binnary $binnumorig is decimal $sum"

小提醒:範例中的路徑 /home/chensiyao 請換成自己的家目錄;另外 [ "$rval"="1" ] 這種寫法在部分 shell 下會出問題,等號兩側留空白才是穩妥寫法。

Copyright © Linux教程網 All Rights Reserved