centos  shell脚本编程2 if 判断  case判断   shell脚本中的循环  for   while   shell中的函数  break  continue  test 命令   第三十六节课

return用在函数中
exit用在shell当中 直接退出整个脚本,整个子shell或当前shell
break退出循环

上半节课

if 判断
case判断
shell脚本中的循环

下半节课

for
while
shell中的函数
break
continue

课程大纲(继续上节课的)

7. if 判断一些特殊用法
if [ -z $a ] 这个表示当变量a的值为空时会怎么样 if [ -z $a ];then ehco "\$a is null" ok; fi
if grep -q '123' 1.txt; then 表示如果1.txt中含有'123'的行时会怎么样
if [ ! -e file ]; then 表示文件不存在时会怎么样
if (($a<1)); then …等同于 if [ $a -lt 1 ]; then… [ ] 中不能使用<,>,==,!=,>=,<=这样的符号

8. shell中的case判断
格式: case 变量名 in
value1)  #匹配value1
command
;;
value2)  #匹配value2
command
;;
*)   #表示匹配任何东西,可以用来检测非法输入
commond
;;
esac

在case程序中,可以在条件中使用|,表示或的意思, 比如
2|3)
command
;;

当变量为2或者3时,执行该部分命令。
注意:case语句里面不能写判断 case xx in >80 ;; >60 是不能的

案例:

#!/bin/bash
read -p "Please input a number: " n if [ -z $n ]
then
echo "Please input a number."
exit
fi n1=`echo $n|sed 's/[-0-9]//g'` if [ ! -z $n1 ]
then
echo "Please input a number."
exit
#elif [ $n -lt 0 ] || [ $n -gt 100 ]
#then
# echo "The number range is 0-100."
# exit
fi if [ $n -lt ]
then
tag=
elif [ $n -ge ] && [ $n -lt ]
then
tag=
elif [ $n -ge ] && [ $n -lt ]
then
tag=
elif [ $n -ge ] && [ $n -le ]
then
tag=
else
tag=
fi case $tag in
)
echo "不及格"
;;
)
echo "及格"
;;
|)
echo "优秀"
;;
*) #匹配任何东西,检测非法输入
echo "The number range is 0-100."
;;
esac 不能写在 ) 前面
*)
echo "The number range is 0-100."
;;

9. shell脚本中的循环
seq命令
默认从1开始
seq 1 20 等价于 seq 20
seq -1 -20
seq 10 -1 1 倒数 -1为步长
for循环 语法结构: for 变量名 in 条件; do … done

案例1:

#!/bin/bash
sum=
for i in `seq `
do
sum=$[$sum+$i]
echo $i
done
echo $sum

案例2:
注意:ls跟find不一样,find会显示绝对路径,ls不会,所以要加/etc/$a,或者在脚本开头加cd /etc/

#!/bin/bash
cd /etc/
for a in `ls /etc/`
do if [ -d /etc/$a ]
then
ls -d /etc/$a
fi
done

结果
# sh for.sh
/etc/abrt
/etc/acpi
/etc/alsa
/etc/alternatives
/etc/audisp
/etc/audit
。。。

案例3:
循环打印一个文本文件,默认以空格为换行符,不是回车,所以还需要用sed处理,不能用cat

#!/bin/bash
n=`wc -l .txt |awk '{print $1}'`
for i in `seq $n`
do
sed -n "$i"p .txt
done

while 循环语法结构: while 条件; do … done 死循环用:表示
案例1:

#!/bin/bash
while :
do
load=`w|head -|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
if [ $load -gt ]
then
top -bn |mail -s "load is high: $load" asldkfls@.com
fi
sleep
done

案例2:

#!/bin/bash

while :
do
read -p "Please input a number: " n
if [ -z $n ]
then
echo "你需要输入东西"
continue
fi n1=`echo $n|sed 's/[-0-9]//g'` if [ ! -z $n1 ]
then
echo "你只能输入一个纯数字"
continue
fi
break
done
echo $n

break直接结束本层循环;

#!/bin/bash
for i in `seq `
do
echo $i
if [ $i == ]
then
break
fi
echo $i
done
echo aaaaaaa

continue忽略continue之下的代码,直接进行下一次循环

#!/bin/bash
for i in `seq `
do
echo $i
if [ $i == ]
then
continue
fi
echo $i
done
echo $i

exit 直接退出shell

#!/bin/bash
for i in `seq `
do
echo $i
if [ $i == ]
then
exit
fi
echo $i
done
echo aaaaaaa

10. shell中的函数
函数就是把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字即可。
格式: function f_name() {
command
}
函数必须要放在最前面

函数调用函数,被调用函数需要先在函数前定义

注意:命令和花括号之间要有空格

ping_fun(){
echo }
正确应该是
ping_fun(){
echo
}
或者
ping_fun(){
echo }

案例1:

#!/bin/bash
input() {
echo $
}

案例2:

#!/bin/bash
sum() {
s=$[$+$]
echo $s #或者return $s
} sum

echo $?
3

案例3:

#!/bin/bash
ip() {
ifconfig |grep -A1 "$1 " |grep addr |awk '{print $2}'|awk -F':' '{print $2}'
} read -p "Please input the eth name: " e
myip=`ip $e`
echo "$e address is $myip"

函数里可以export 全局变量

案例4:

猜数字游戏
$RANDOM 生成随机数 $[$RANDOM%] 100之内的随机数 取余 #!/bin/bash
n=$[$RANDOM%]
while :
do
read -p "pleas input a number:" n1
n2=`echo $n1 |sed 's/[0-9]//g'`
if [ ! -z $n2 ]
then
echo "your number is not a number"
continue
fi
if [ $n1 == $n ]
then
echo "right"
echo $n
elif [ $n1 -gt $n ]
then
echo "bigger"
continue
else
echo "smaller"
continue
fi
done

案例5:

#ping函数
#!/bin/bash
#write by -- ping_fun(){
if ping -c $ $ > /dev/null >&
then
return
else
return
fi
} host=192.168.12.253
count= while :
do
ping_fun $count $host
if [ $? -eq ]
then
echo "$host is up"
else
echo "$host is down " |mail -s "$host is down " abc@.com
fi
sleep
done

11. shell练习题
编写shell脚本,计算1-100的和;
编写shell脚本,要求输入一个数字,然后计算出从1到输入数字的和,要求,如果输入的数字小于1,则重新输入,直到输入正确的数字为止;
编写shell脚本,把/root/目录下的所有目录(只需要一级)拷贝到/tmp/目录下;
编写shell脚本,批量建立用户user_00, user_01, ... user_100并且所有用户同属于users组;
编写shell脚本,截取文件test.log中包含关键词 ‘abc’ 的行中的第一列(假设分隔符为 ”:” ),然后把截取的数字排序(假设第一列为数字),然后打印出重复次数超过10次的列;

扩展学习:
select用法 http://www.apelearn.com/bbs/thread-7950-1-1.html


扩展阅读

shell中的select用法 [复制链接]
select也是循环的一种,它比较适合用在用户选择的情况下。
比如,我们有一个这样的需求,运行脚本后,让用户去选择数字,选择1,会运行w命令,选择2运行top命令,选择3运行free命令,选择4退出。输入序号1、2、3、4

脚本这样实现:

#!/bin/bash
echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
echo
select command in w top free quit #从数字1开始 只能输入数字 1w 2top 3free 4quit
do
case $command in
w)
w
;;
top)
top
;;
free)
free
;;
quit)
exit
;;
*)
echo "Please input a number:(1-4)."
;;
esac
done

执行结果如下:
sh select.sh
Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit

1) w
2) top
3) free
4) quit
#? 1
16:03:40 up 32 days, 2:42, 1 user, load average: 0.01, 0.08, 0.08
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 61.135.172.68 15:33 0.00s 0.02s 0.00s sh select.sh

#? 3
total used free shared buffers cached
Mem: 1020328 943736 76592 0 86840 263624
-/+ buffers/cache: 593272 427056
Swap: 2097144 44196 2052948
#?

我们发现,select会默认把序号对应的命令列出来,每次输入一个数字,则会执行相应的命令,命令执行完后并不会退出脚本。它还会继续让我们再次输如序号。序号前面的提示符,我们也是可以修改的,利用变量PS3即可,再次修改脚本如下:

#!/bin/bash
PS3="Please select a number: "
echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
echo select command in w top free quit
do
case $command in
w)
w
;;
top)
top
;;
free)
free
;;
quit)
exit
;;
*)
echo "Please input a number:(1-4)."
esac
done

如果想要脚本每次输入一个序号后就自动退出,则需要再次更改脚本如下:

#!/bin/bash
PS3="Please select a number: "
echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
echo #换行 select command in w top free quit
do
case $command in
w)
w;exit
;;
top)
top;exit
;;
free)
free;exit
;;
quit)
exit
;;
*)
echo "Please input a number:(1-4).";exit
esac
done

echo换行

实际上是echo 一个空行

echo 相当于 echo ' '

cat bb.sh

#!/bin/bash
echo 'sf'
echo
echo 'ii'

sh bb.sh
sf

ii


test 命令用法详解
--http://blog.csdn.net/duguteng/article/details/7725845

基本格式:
test expression
expression为test命令构造的表达式。
这里expression是test命令可以理解的任何有效表达式,该简化格式将是读者可能会踫见的最常用格式
返回值:
test命令或者返回0(真) 或者返回1(假).

方式:
表达式判断
字符串比较
数字比较
文件比较

也就是说
    test option file
可以全部改写成:
    [ option file ]
例如:
 test –w File
改写成    
[ –w File ]

【示例】
//判断第一个参数是否为空字符串,不空则打印
if test -n "$1"
then
echo "$1"
fi
测试,放到文件当中
#!/bin/sh
if test -n "$1"
then
echo "$1"
fi
执行
chmod +x test.sh
./test.sh www.linuxpig.com

if  test  $? -eq 0

判断返回值是否等于0


shell中自带的正则匹配
http://bbs.chinaunix.net/thread-4125147-1-1.html
if [[ ! "$arch" =~ x86 ]];then
    echo "$2" > /etc/setup/last-mirror
    echo "" > /etc/setup/last-arch

例子
<List>
    <Job id="1" name="abc"/>
    <Job id="2" name="zyz"/>
    <Job id="3" name="beew"/>
</List>

想要得到这个结果。
abc | 1
zyz | 2
beew | 3

#!/bin/bash

while read  line; do
  if [[ $line =~ id=\"([0-9]+).*name=\"([^\"]*) ]]; then
    echo "${BASH_REMATCH[2]} | ${BASH_REMATCH[1]}"
  fi
done < file

如果你对sed 里的 \1 \2 的用法很熟的话,就应该很快的明白 BASH_REMATCH[1] 和 BASH_REMATCH[2] 代表了什么。

f

centos shell脚本编程2 if 判断 case判断 shell脚本中的循环 for while shell中的函数 break continue test 命令 第三十六节课的更多相关文章

  1. centos shell脚本编程1 正则 shell脚本结构 read命令 date命令的用法 shell中的逻辑判断 if 判断文件、目录属性 shell数组简单用法 $( ) 和${ } 和$(( )) 与 sh -n sh -x sh -v 第三十五节课

    centos   shell脚本编程1 正则  shell脚本结构  read命令  date命令的用法  shell中的逻辑判断  if 判断文件.目录属性  shell数组简单用法 $( ) 和$ ...

  2. centos shell编程5 LANMP一键安装脚本 lamp sed lnmp 变量和字符串比较不能用-eq cat > /usr/local/apache2/htdocs/index.php <<EOF重定向 shell的变量和函数命名不能有横杠 平台可以用arch命令,获取是i686还是x86_64 curl 下载 第三十九节课

    centos shell编程5  LANMP一键安装脚本 lamp  sed  lnmp  变量和字符串比较不能用-eq  cat > /usr/local/apache2/htdocs/ind ...

  3. centos linux系统日常管理3 服务管理ntsysv,chkconfig,系统日志rsyslog,last ,lastb ,exec,xargs,dmesg,screen,nohup,curl,ping ,telnet,traceroute ,dig ,nc,nmap,host,nethogs 第十六节课

    centos linux系统日常管理3  服务管理ntsysv,chkconfig,系统日志rsyslog,last ,lastb ,exec,xargs,dmesg,screen,nohup,cur ...

  4. centos MySQL主从配置 ntsysv chkconfig setup命令 配置MySQL 主从 子shell MySQL备份 kill命令 pid文件 discuz!论坛数据库读写分离 双主搭建 mysql.history 第二十九节课

    centos  MySQL主从配置 ntsysv   chkconfig  setup命令  配置MySQL 主从 子shell  MySQL备份  kill命令  pid文件  discuz!论坛数 ...

  5. centos Linux系统日常管理2 tcpdump,tshark,selinux,strings命令, iptables ,crontab,TCP,UDP,ICMP,FTP网络知识 第十五节课

    centos  Linux系统日常管理2  tcpdump,tshark,selinux,strings命令, iptables ,crontab,TCP,UDP,ICMP,FTP网络知识 第十五节课 ...

  6. centos Linux系统日常管理1 cpuinfo cpu核数 命令 w, vmstat, uptime ,top ,kill ,ps ,free,netstat ,sar, ulimit ,lsof ,pidof 第十四节课

    centos Linux系统日常管理1  cpuinfo cpu核数   命令 w, vmstat, uptime ,top ,kill ,ps ,free,netstat ,sar, ulimit ...

  7. 程序员编程艺术第三十六~三十七章、搜索智能提示suggestion,附近点搜索

    第三十六~三十七章.搜索智能提示suggestion,附近地点搜索 作者:July.致谢:caopengcs.胡果果.时间:二零一三年九月七日. 题记 写博的近三年,整理了太多太多的笔试面试题,如微软 ...

  8. centos lamp/lnmp阶段复习 以后搬迁discuz论坛不需要重新安装,只需修改配置文件即可 安装wordpress 安装phpmyadmin 定时备份mysql两种方法 第二十五节课

    centos  lamp/lnmp阶段复习 以后搬迁discuz论坛不需要重新安装,只需修改配置文件即可 安装wordpress  安装phpmyadmin  定时备份mysql两种方法  第二十五节 ...

  9. centos LAMP第一部分-环境搭建 Linux软件删除方式,mysql安装,apache,PHP,apache和php结合,phpinfo页面,ldd命令 第十九节课

    centos LAMP第一部分-环境搭建  Linux软件删除方式,mysql安装,apache,PHP,apache和php结合,phpinfo页面,ldd命令 第十九节课 打命令之后可以输入: e ...

随机推荐

  1. c++ json cpp

    一 编译链接 1 在相应官网下载jsoncpp 2 解压得到jsoncpp-src-0.5.0文件 3 打开jsoncpp-src-0.5.0 -> makefiles -> vs71 - ...

  2. 【Matlab】运动目标检测之“帧差法”

    videoObj = VideoReader('4.avi');%读视频文件 nframes = get(videoObj, 'NumberOfFrames');%获取视频文件帧个数 : nframe ...

  3. PHP大小写是否敏感问题

    一.大小写敏感 1. 变量名区分大小写 所有变量均区分大小写,包括普通变量以及$_GET,$_POST,$_REQUEST,$_COOKIE,$_SESSION,$GLOBALS,$_SERVER,$ ...

  4. jquery 中的回调函数,回调函数(callback)是什么?

    知乎上果然大牛比较多 大神解释如下: 你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货.在这个例子里, ...

  5. Android中使用UncaughtExceptionHandler来处理未捕获的异常

    原文在sparkyuan.me上.转载注明出处:http://sparkyuan.github.io/2016/03/28/使用UncaughtExceptionHandler来处理未捕获的异常/ 全 ...

  6. SQLServer------聚集索引和非聚集索引的区别

    转载: http://www.cnblogs.com/flashicp/archive/2007/05/08/739245.html 建立非聚集索引(vid不是主键) create index idx ...

  7. mybatis由浅入深day02_6延迟加载_延迟加载总结

    6 延迟加载 6.1 什么是延迟加载 需要查询关联信息时,使用mybatis延迟加载特性可有效的减少数据库压力,首次查询只查询主要信息,关联信息等用户获取时再加载. resultMap可以实现高级映射 ...

  8. POJ 1837 Balance(01背包变形, 枚举DP)

    Q: dp 数组应该怎么设置? A: dp[i][j] 表示前 i 件物品放入天平后形成平衡度为 j 的方案数 题意: 有一个天平, 天平的两侧可以挂上重物, 给定 C 个钩子和G个秤砣. 2 4 - ...

  9. docker images 详解

    docker images 用于查看本地已下载的镜像 [root@localhost ~]$ docker images REPOSITORY TAG IMAGE ID CREATED SIZE ce ...

  10. 在centos命令行下安装软件

    考虑到用linux纯命令行模式时,通常都是用作服务器,所以,一般主要是安装一个php.mysql.apache的集成环境和ftp服务器,在这里用xampp集成包即可解决所有问题,在这里说一下我自己的做 ...