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. R.java文件介绍

    HelloWorld工程中的R.java文件 package com.android.hellworld; public final class R {     public static final ...

  2. Android热补丁技术—dexposed原理简析(手机淘宝采用方案)

    上篇文章<Android无线开发的几种常用技术>我们介绍了几种android移动应用开发中的常用技术,其中的热补丁正在被越来越多的开发团队所使用,它涉及到dalvik虚拟机和android ...

  3. SoC嵌入式软件架构设计

    内存是SoC(System on Chip,片上系统)集成设计的重要模块,是SoC中成本比重较大的部分.内存管理的软硬件设计是SoC软件架构设计的重要一环,架构设计师必须要在成本和效率中取得平衡,做到 ...

  4. Mina源码阅读笔记(四)—Mina的连接IoConnector2

    接着Mina源码阅读笔记(四)-Mina的连接IoConnector1,,我们继续: AbstractIoAcceptor: 001 package org.apache.mina.core.rewr ...

  5. mac os x下的程序快速切换快捷键

    按下command + tab键正向切换程序 按下command + shift + tab键反向切换程序 按下command + tab键选择程序后,仍然按下command键不放,然后按下optio ...

  6. 简单开发Apple Watch的步骤

    好久没写博客了,自己这两年自从孩子出世,也慢慢懈怠了.实在有点对不住了,换了个新公司,也有点时间可以写写东西了.  前几天苹果刚刚发布Apple Watch,Xcode6也更新了watchKit,正好 ...

  7. Redis客户端ServiceStack.Redis的简单使用

    在nuget中下载ServiceStack.Redis,但是运行之后会出现一个问题: Exception: "Com.JinYiWei.Cache.RedisHelper"的类型初 ...

  8. angular1.0 app

    angular 1.0 简单的说一下就是ng启动阶段是 config-->run-->compile/link config阶段是给了ng上下文一个针对constant与provider修 ...

  9. UML类图中连接线与箭头的含义(转)

    UML类图是描述类之间的关系 概念 类(Class):使用三层矩形框表示. 第一层显示类的名称,如果是抽象类,则就用斜体显示. 第二层是字段和属性. 第三层是类的方法. 注意前面的符号,'+'表示pu ...

  10. 【程序员札记#学习&&塑形# 】2018年5月04号

      回顾   工作:pendding 学习:看算法导论第一章,leetcode还在做(本身翻译错误,被误导了). 体会: 1) 浩俊之前推荐让我看的<算法导论>,昨天再回过头看,里面很多确 ...