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. 在多台PC上进行ROS通讯-学习笔记

    首先,致谢易科(ExBot)和ROSWiki中文社区. 重要参考文献: Running ROS across multiple machines http://wiki.ros.org/ROS/Tut ...

  2. Spring AOP (二)

    下面介绍@AspectJ语法基础 一.切点表达式函数 AspectJ的切点表达式由关键字和操作参数组成,如execution(* greetTo(..)) 的切点表达式,execution为关键字,而 ...

  3. 聊聊String

    当我们最开始学习java的时候,老师会告诉我们字符串的比较需要用equals(); 真的是这样的吗? 我们看看下面的例子 public class TestString { public static ...

  4. 使用API获取(默认付款条件和到期日)

    1. 目的:使用API取到应收事务处理的付款条件(实现标准功能的付款条件和到期日)2. 实现方法:调用 ARP_TRX_DEFAULTS_3.get_term_default获得付款条件 3.实现代码 ...

  5. Java进阶(十二)JDK版本错误之Unsupported major.minor version 51.0(jdk版本错误)

    错误:Unsupported major.minor version 51.0(jdk版本错误) 如果在win7下开发项目是使用的jdk版本和项目运行服务器jdk版本不同就会出现上面的问题. 用jdk ...

  6. 如何搭建modem编译环境

    [DESCRIPTION] (1)MT6577以及之前的chip平台(如MT6575,73等) 的modem编译环境和MTK的Feature Phone的编译环境一样,即Windows+RVCT (2 ...

  7. 【56】java本地文件File类详解

    1.java类的介绍 public class File extends Object implements Serializable, Comparable<File> 文件和目录路径名 ...

  8. 分布式版本库——Windows下Git的环境部署以及在GitHub上开源自己的项目

    分布式版本库--Windows下Git的环境部署以及在GitHub上开源自己的项目 这几天着实忙的焦头烂额,可惜不是搞技术,今天周日,难得闲下来,写篇大家都想学习的Git教程,其实廖雪峰老师的网站已经 ...

  9. Android群英传笔记——第一章:Android体系与系统架构

    Android群英传笔记--第一章:Android体系与系统架构 图片都是摘抄自网络 今天确实挺忙的,不过把第一章的笔记做一下还是可以的,嘿嘿 1.1 Google的生态圈 还是得从Android的起 ...

  10. kettle控件 add a checksum

    This step calculates checksums for one or more fields in the input stream and adds this to the outpu ...