几个简单的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"

  • 1
  • 2
  • 下一页

相关内容