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. 排序算法(二)Sort with Swap(0,*)

    对于一个由0到N-1的序列,如果只能交换0和另一个数的位置,求多少次能够将序列变为递增序列. 输入为<N> <序列>(N和序列之间有一个空格,序列元素之间均有一个空格). 设序 ...

  2. LeetCode之“树”:Symmetric Tree && Same Tree

    Symmetric Tree 题目链接 题目要求: Given a binary tree, check whether it is a mirror of itself (ie, symmetric ...

  3. 为macbook双系统的windows装驱动

    网上有很多装双系统教程,这里就不再累赘,但是自己发现装完后驱动怎么装并没有交代清楚. 研究后发现,在作为驱动盘的U盘里,BootCamp文件夹下有个setup.exe 运行此程序便进行驱动的安装.

  4. Android ROM开发(二)——ROM架构以及Updater-Script脚本分析,常见的Status错误解决办法

    Android ROM开发(二)--ROM架构以及Updater-Script脚本分析,常见的Status错误解决办法 怪自己二了,写好的不小心弄没了,现在只好重新写一些了,上篇简单的配置了一下环境, ...

  5. 苹果新的编程语言 Swift 语言进阶(四)--字符串和收集类型

    一.字符串( String  )和字符类型(Character) 字符串是一种字符的带次序的收集类型(相当于数组),字符是字符串中的元素. 在Swift 语言中,字符串是编码独立的Unicode字符的 ...

  6. objective-c中线程编程一例

    /* print with threads : print every file's first n char contents under the path that pass to this pr ...

  7. JS实现鼠标滚动事件,兼容IE9,FF,Chrome.

    <!-- 废话不多说,直接贴代码 --><script type="text/javascript" src="jquery.min.js"& ...

  8. 实现Android Native端爆破源码

    尝试在移动端so侧做一些内存修改,使之走向不通的逻辑,一下为将要爆破的APP源码 JAVA侧: package com.example.grady.sectestone; import android ...

  9. Error filterStart的问题

    今天出现这个问题 严重: Error filterStart org.apache.catalina.core.StandardContext start 严重: Context startup fa ...

  10. 自设table表格,获取内容,并经弹出框的url传参,获取结果显示在弹出框,并加载合计

    table表格,选择框 form id="editForm1"> <table class="table_form"> <td > ...