shell与其他语言一样也支持for、while循环

for循环的一般格式如下:

 #!/bin/sh

 for 变量 in 列表
do
command
command
command
.........
command n
done

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
列表也可以是一个文件:
in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

 #!/bin/sh

 for line in
do
echo "line is $line"
done

结果:

[root@localhost 1st]# sh test.sh
line is 1
line is 2
line is 3
line is 4
line is 5
line is 6
line is 7

下面用for循环读一个文件:

查看文件内容

 [root@localhost 1st]# cat test.txt
hello
wolrd
hello
shell
[root@localhost 1st]#

code:

 #!/bin/sh

 FILE=./test.txt

 for line in $(<$FILE)
do
echo "line is: $line"
done

Results:

 [root@localhost 1st]# sh xx.sh
line is: hello
line is: wolrd
line is: hello
line is: shell
[root@localhost 1st]#

while循环的一般格式如下:

 while command
do statement done

code:

 #!/bin/sh

 i=
sum=
while [ $i -le ]
do
sum=$(($sum + $i))
i=$(($i + ))
done
echo "sum is $sum"
rusults:
 [root@localhost 1st]# sh xx.sh
sum is
[root@localhost 1st]#

if语句的一般格式如下:

 if ....; then
....
elif ....; then
....
else
....
fi

if 条件语句:

文件表达式:

 [ -f "somefile" ] :  判断是否是一个文件
[ -x "/bin/ls" ] :   判断/bin/ls是否存在并有可执行权限
[ -n "$var" ] :    判断$var变量是否有值
[ "$a" = "$b" ] :  判断$a和$b是否相等
-r file       用户可读为真
 -w file       用户可写为真
 -x file       用户可执行为真
 -f file       文件为正规文件为真
 -d file       文件为目录为真
 -c file       文件为字符特殊文件为真
 -b file       文件为块特殊文件为真
 -s file       文件大小非0时为真
 -t file       当文件描述符(默认为1)指定的设备为终端时为真

字符串表达式:

[string string_operator string]

这里string_operator可为如下几种:

 =     两个字符串相等。
!= 两个字符串不等。
-z 空串。
-n 非空串

eg:

  #!/bin/sh

  NUMS="hello"
[ $NUMS = "hello" ] echo $?

results:

 [root@localhost 1st]# sh xx.sh
 

整数表达式:

 -eq   数值相等。
-ne 数值不相等。
-gt 第一个数大于第二个数。
-lt 第一个数小于第二个数。
-le 第一个数小于等于第二个数。
-ge 第一个数大于等于第二个数。

Eg:

 #!/bin/sh

 NUMS=
if [ $NUMS -eq "" ]; then echo "equal"
else
echo "not equal"
fi

results:

 [root@localhost 1st]# sh xx.sh
equal

下满贴出一个用shell写的简单图书管理系统:

 #!/bin/bash
#Name:Books Management System(BMS)
#Author:DREAM
file=books.txt
function information
{
echo "Books Management System(BMS)"
echo "---------------------------"
echo -e " 1: ADD Books"
echo -e " 2: Show Books"
echo -e " 3: Select Books"
echo -e " 4: Delete Books"
echo -e " 5: Exit System"
#echo
echo "---------------------------"
read -p "please input your choice:" num
echo case "$num" in
) Add
;;
) Show
;;
) Select
;;
) Delete
;;
) exit
;;
*) information
;;
esac
} function Add
{
echo -e "please books information eg:(English 101 Jerry)"
echo
read -p "please input books name: " books_name
read -p "please input books number: " books_num
read -p "please input books author: " books_author echo -e "$books_name\t$books_num\t$books_author" >>$file && {
echo "Add Books success"
echo "---------------------------"
}
if [ $? -ne ]
then
echo "Add Books failure"
fi information
} function Show
{
echo -e "Bname\tBnum\tBauthor"
grep -Ev "^$" $file
echo "-----------------------"
echo
information
} function Search_menu
{
echo "-----------------------"
echo -e " 1: Search By Bname"
echo -e " 2: Search By Bnum"
echo -e " 3: Search By Bauthor"
echo -e " 4: Eixt Search System"
echo
echo "-----------------------"
} function Select
{
Search_menu
read -p "please input your choice:" ch
case "$ch" in
)
read -p "please input books name: " name
echo -e "Bname\tBnum\tBauthor\n-------------------------"
awk '{if($1~/^'$name'/) print $0}' $file
echo "-------------------------"
if [ $? -ne ]
then
echo "the file no exist"
fi
;;
)
read -p "please input books number: " num
echo -e "Bname\tBnum\tBauthor\n-------------------------"
awk -v s=$num '$2==s {print $0}' $file >/dev/null
echo "-------------------------"
if [ $? -ne ]
then
echo "the file no exist"
fi
echo $?
;;
)
read -p "please input books author: " author
echo -e "Bname\tBnum\tBauthor\n-------------------------"
awk '{if($3~/'$author'/) print $0}' $file
echo "-------------------------"
if [ $? -ne ]
then
echo "the file no exist"
fi
echo $? ;;
) exit
;;
*) Select
;;
esac
echo
information
} function Delete
{
read -p "please input your want delete boos number:" num
sed -i "/$num/d" $file if [ $? -ne ]
then
echo "success failure"
fi information
} information

利用popen快速获取一个shell命令的返回值

优点:避免了生成临时文件

函数原型:

  #include <stdio.h>

        FILE *popen(const char *command, const char *type);

        int pclose(FILE *stream);

函数说明:

  popen()函数通过创建一个管道,调用fork()产生一个子进程,执行一个shell以运行命令来开启一个进程。这个管道必须由pclose()函数关闭,而不是fclose()函数。pclose()函数关闭标准I/O流,等待命令执行结束,然后返回shell的终止状态。如果shell不能被执行,则pclose()返回的终止状态与shell已执行exit一样。

  type参数只能是读("r")或者写("w")中的一种,得到的返回值(标准I/O流)也具有和type相应的只读或只写类型。如果type是"r"则文件指针连接到command的标准输出;如果type是"w"则文件指针连接到command的标准输入。

  command参数是一个指向以NULL结束的shell命令字符串的指针。这行命令将被传到bin/sh并使用-c标志,shell将执行这个命令。

  popen()的返回值是个标准I/O流,必须由pclose来终止。前面提到这个流是单向的(只能用于读或写)。向这个流写内容相当于写入该命令的标准输入,命令的标准输出和调用popen()的进程相同;与之相反的,从流中读数据相当于读取命令的标准输出,命令的标准输入和调用popen()的进程相同。

返回值:

  如果调用fork()或pipe()失败,或者不能分配内存将返回NULL,否则返回标准I/O流。popen()没有为内存分配失败设置errno值。如果调用fork()或pipe()时出现错误,errno被设为相应的错误类型。如果type参数不合法,errno将返回EINVAL。

下面是使用popen获取主机中虚拟机个数的范例:

 #include <stdio.h>
#include <string.h> int main()
{
FILE *fp;
size_t value = ;
int nums;
char cmd[] = {};
int guestnums; strcpy(cmd, "virsh list --all | sed -n '3, $p' | grep -v '^$' | wc -l"); /*使用popen获取shell命令返回值*/
if((fp = popen(cmd, "r")) != NULL) { if(fgets((char *)&nums, , fp))
{
guestnums = atoi((char *)&nums);
}
} printf("%d\n", guestnums);
pclose(fp); return ; }

  

shell 中的for、while循环及if语句的更多相关文章

  1. shell编程学习笔记(十一):Shell中的while/until循环

    shell中也可以实现类似java的while循环 while循环是指满足条件时,进行循环 示例: #! /bin/sh index=10 while [ $index -gt 0 ] do inde ...

  2. linux shell中 if else for循环以及大于、小于、等于逻辑表达式的历程

    作者:邓聪聪 比如比较字符串.判断文件是否存在及是否可读等,通常用"[]"来表示条件测试. 注意:这里的空格很重要.要确保方括号的空格.笔者就曾因为空格缺少或位置不对,而浪费好多宝 ...

  3. (二)shell中case语句、程序传参、while

    2.2.6.1.case语句(1)shell中的case语句和C语言中的switch case语句作用一样,格式有差异(2)shell中的case语句天生没有break,也不需要break,和C语言中 ...

  4. 『忘了再学』Shell基础 — 32、Shell中test测试命令详解

    目录 1.test测试命令 (1)test命令介绍 (2)test命令使用方式 (3)示例 2.按照文件类型进行判断 3.按照文件权限进行判断 4.两个文件之间进行比较 5.两个整数之间比较 6.字符 ...

  5. bash shell中测试命令

    bash shell中测试命令 test命令提供了if-than语句中测试不同条件的途径.如果test命令中列出的条件成立,test命令就会退出并返回退出状态吗0 .这样if-than语句就与其他编程 ...

  6. shell中的循环

    shell中的循环 for循环 类似于C语言的步长控制 例如: ;i<=;i++)); ); done 将1到10,依次乘以4,然后打印出来. 这里顺便提一下,shell里面表达式的计算,可以有 ...

  7. (八)shell中的循环结构

    1.for循环(1)要求:能看懂.能改即可.不要求能够完全不参考写出来.因为毕竟嵌入式并不需要完全重新手写shell,系统管理员(服务器运维人员,应用层系统级管理开发的才需要完全掌握shell) 这里 ...

  8. shell中for循环

    shell中for循环总结 最常用的就是遍历操作某一类文件,比如批量建索引. for i in `ls` do samtools faidx $i done 注意:for末尾不需要冒号(:),循环的代 ...

  9. shell中for循环总结

    关于shell中的for循环用法很多,一直想总结一下,今天网上看到上一篇关于for循环用法的总结,感觉很全面,所以就转过来研究研究,嘿嘿... 1. for((i=1;i<=10;i++));d ...

  10. Linux shell编程 4 ---- shell中的循环

    1 for循环 1 for语句的结构 for variable in values; do statement done 2 for循环通常是用来处理一组值,这组值可以是任意的字符串的集合 3 for ...

随机推荐

  1. 并发服务器--02(基于I/O复用——运用epoll技术)

    本文承接自上一博文I/O复用——运用Select函数. epoll介绍 epoll是在2.6内核中提出的.和select类似,它也是一种I/O复用技术,是之前的select和poll的增强版本. Li ...

  2. 一键安装 redmine on rhel6.4

    一键安装 redmine on rhel6.4 一键式安装redmine省去了大量不必要的时间.下载:bitnami-redmine-2.5.2-1-linux-x64-installer.run. ...

  3. SharePoint 部件通过EditorPart自定义属性面板

    需求:编写一个新闻展示的WebPart,要求可以分类,类别是从WebService中获取的字符串,要求可以在属性中勾选分类,显示该分类的信息,分类可能会增加.我要做的就是动态生成属性中的新闻类别,至于 ...

  4. SharePoint 2010 -- .Net托管客户端模型简单示例

    .Net托管客户端模型,是SharePoint2010推出的三种客户端模型".NET托管"."ECMAScript"."Sliverlight&quo ...

  5. jquery左右折叠框

    网站左右折叠框: <!DOCTYPE html> <html> <style> #Kefclose,#Kefopen{position:absolute;left: ...

  6. 遍历输出图片加hover

    1. $(".icon a>div").hover(function () { var slls = $(this).attr("class"); sll ...

  7. spring3.1文档目录翻译

    整理google共享磁盘找到了2014年翻译的spring官方文档的目录,分享出来可能会对英语不好的同学有些帮助吧. spring3.1官方文档目录-中文 spring3.1官方文档-英文 关于作者

  8. 教你一步步发布一个开源库到 JCenter

    今天想来分享下,如何一步步自己发布一个开源库到 JCenter 这方面的博客网上已经特别多了,所以本篇并不打算仅仅只是记录流程步骤而已,而是尽可能讲清楚,为什么需要有这个步骤,让大伙知其然的同时还知其 ...

  9. 没人看系列-----html随笔

    <!DOCTYPE> 目录 没人看系列-----html/css详解 前言 不多说这段时间写了好多好多前端的东西,以至于自己重新返回看了一遍前端的所有技术.故此做个总结,准备学东西的请绕行 ...

  10. 中国的UED们

    UED网址导航:http://www.ux265.com/ 天猫UED:http://ued.tmall.com/ 一淘UED:http://ux.etao.com/ 淘宝UED:http://ued ...