歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> 幾個簡單的Shell實例親測

幾個簡單的Shell實例親測

日期:2017/3/1 10:13:45   编辑:SHELL編程
本來剛接觸shell腳本編程,在網上看到有好多實例,於是乎便自己跟著敲敲,受益啊。

1.獲取本機IP

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

2.yes/no返回不同結構(case的應用 )


#!/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


3.讀取某一文件的指定行

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


4.給函數傳遞參數

#!/bin/bash
#定義函數
p_num()
{
num=$1
echo $num
}
#使用for循環
for n in $*
do
#把循環到的參數傳遞到函數
p_num $n
done
~


5.創建文件夾

#!/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 sussesfull!"
break
fi
done


6.二進制轉十進制

#!/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()
{
# print an error and exit
echo "$1"
exit 1
}


lastchar()
{
# is the last num
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 binnumorig!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

#若不為1,則減1,後將rval取參數前(n-1)位
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
sum=0
weight=1

#判斷若參數為空則調用help函數
[ -z "$1" ]&&help

#賦值
binnum="$1"
binnumorig="$1"

#開啟循環,若參數不為空,循環
while [ -n "$binnum" ];do
#調函數lastchar,返回參數最後一個字節
lastchar "$binnum"

#若最後一個字節為1
if [ "$rval"="1" ];then
sum=`expr "$weight" "+" "$sum"`
fi

#循環,返回參數(n-1)位值
chop "$binnum"

#將(n-1)的參數賦於binnum
binnum="$rval"

#同時weight*2,因為二進制的規律是1,2,4,8...
weight=`expr "$weight" "*" 2`

#直到返回的binnum為空,退出
done

#打印結果
echo "binnary $binnumorig is decimal $sum"

Copyright © Linux教程網 All Rights Reserved