博文结构

什么是shell

简单编辑shell

循环语句

一.什么是shell及作用

Shell字面理解就是个“壳”,是操作系统(内核)与用户之间的桥梁,充当命令解释器的作用,将用户输入的命令翻译给系统执行。Linux中的shell与Windows下的DOS一样,提供一些内建命令(shell命令)供用户使用,可以用这些命令编写shell脚本来完成复杂重复性的工作

什么是脚本?

脚本就是由Shell命令组成的件,这些命令都是可执行程序的名字,脚本不用编译即可运行。它通过解释器解释运行,所以速度相对来说比较慢。

shell脚本的优点

1.自动化管理的重要依据

2.追踪与管理系统的重要工

3.简单侦测功能

4.连续指令单一化

5.简易的数据处理

6.跨平台支持与学习历程较短

编写shell脚本注意事项

指令的执行是从上而下、从左而右的分析与执行;

指令的下达就如同之前提到的:指令、选项与参数间的多个空白都会被忽略掉;

空白行也将被忽略掉,并且 [tab] 按键所推开的空白同样视为空白键;

如果读取到一个 Enter 符号(CR),就尝试开始执行该行(或该串)命令;

至于如果一行的内容太多,则可以使用“ [Enter] ”来延伸至下一行;

“ # ”可做为注解!任何加在 # 后面的数据将全部被视为注解字而被忽略!

执行shell脚本分为四点

直接指令下达: shell.sh 件必须要具备可读与可执行(nx) 的权限,然后:

绝对路径:使用/home/dtsai/shell.sh 来下达指令;相对路径:假设工作目录在/home/dmtsai/,则使用.shel.sh 来执行

*变量"PATH"功能:将shell.sh放在PATH指定的目录内,例如: ~/bin/

以bash程序来执行:通过“bash shell,sh”或“sh shell.sh "来执行

二.简单编辑shell

[root@localhost ~]# vim a.sh

#!/bin/bash

echo -e "hellow \a \n"

exit 0

[root@localhost ~]# chmod a+x a.sh

[root@localhost ~]# sh a.sh

hellow

第一行 #!/bin/bash 在宣告这个 script 使用的 shell 名称:

程序内容的说明:

主要环境变量的宣告:建议务必要将一些重要的环境变量设置好,我个人认为, PATH 与 LANG (如果有使用到输出相关的信息时)是当中最重要的!如此一来,则可让我们这支程序在进行时,可以直接下达一些外部指令,而不必写绝对路径呢!

主要程序部分就将主要的程序写好即可

执行成果告知(定义回传值)一个指令的执行成功与否,可以使用$?这个变量来观察~那么我们也可以利用 exit 这个指令来让程序中断,并且回传一个数值给系统

\a 发出警告声;\n 换行且光标移至行首;

对谈式脚本:变量内容由使用者决定量

随日期变化:利用date进行件的创建

数值运算:简单的加减乘除

对谈式脚本:变量内容由使用者决定量

[root@localhost ~]# vim b.sh

#!/bin/bash

read -p "Please input your first name: " firstname

read -p "Please input your last name: " lastname

echo -e "\nYour full name is: ${firstname} ${lastname}"

[root@localhost ~]# sh b.sh

Please input your first name: x

Please input your last name: a

Your full name is: x a

随日期变化:利用date进行件的创建

[root@localhost ~]# vim x.sh

#!/bin/bash

echo -e "I will use 'touch' command to create 3 files."

read -p "Please input your filename: "

fileuserfilename=${fileuser:-"filename"}

date1=$(date --date='2 days ago' +%Y%m%d)

date2=$(date --date='1 days ago' +%Y%m%d)

date3=$(date +%Y%m%d)

file1=${filename}${date1}

file2=${filename}${date2}

file3=${filename}${date3}

touch "${file1}"

touch "${file2}"

touch "${file3}"

filename: a

[root@localhost ~]# ls \\可以看到创建了3天的件

20191203 20191205 a.sh initial-setup-ks.cfg 公共 视频 档 音乐

20191204 anaconda-ks.cfg b.sh x.sh 模板 图片 下载 桌面

数值运算:简单的加减乘除

[root@localhost ~]# vim q.sh

#!/bin/bash

echo -e "You SHOULD input 2 numbers, I will multiplying them! \n"

read -p "first number: " firstnu

read -p "second number: " secnu

total=$((${firstnu}*${secnu}))

echo -e "\nThe result of ${firstnu} x ${secnu} is ==> ${total}"

[root@localhost ~]# sh q.sh

You SHOULD input 2 numbers, I will multiplying them!

first number: 2

second number: 3

The result of 2 x 3 is ==> 6

利用test指令的测试功能

三.循环语句

if条件测试语句

if条件测试语句可以让脚本根据实际情况自动执行相应的命令。从技术角度来讲,if语句分为单分支结构、双分支结构、多分支结构;其复杂度随着灵活度一起逐级上升。

1.if条件语句的单分支结构由if、then、fi关键词组成,而且只在条件成立后才执行预设的命令,相当于口语的“如果……那么……”。单分支的if语句属于最简单的一种条件判断结构。

案例:

[root@localhost ~]# vim x.sh

#!/bin/bash

read -p "Please input (Y/N): " yn

if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then

echo "OK, continue"

exit 0

fi

if [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then

echo "Oh, interrupt!"

exit 0

fi

echo "I don't know what your choice is" && exit 0

[root@localhost ~]# sh x.sh

Please input (Y/N): Y

OK, continue

[root@localhost ~]# sh x.sh

Please input (Y/N): N

Oh, interrupt!

[root@localhost ~]# sh x.sh

Please input (Y/N): asd

I don't know what your choice is

2.if条件语句的双分支结构由if、then、else、fi关键词组成,它进行一次条件匹配判断,如果与条件匹配,则去执行相应的预设命令;反之则去执行不匹配时的预设命令,相当于口语的“如果……那么……或者……那么……”。if条件语句的双分支结构也是一种很简单的判断结构。

还用上面的案例:

[root@localhost ~]# vim x.sh

#!/bin/bash

read -p "Please input (Y/N): " yn

if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then

echo "OK, continue"

elif [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then

echo "Oh, interrupt!"

else

echo "I don't know what your choice is"

fi

[root@localhost ~]# sh x.sh

Please input (Y/N): Y

OK, continue

3.if条件语句的多分支结构由if、then、else、elif、fi关键词组成,它进行多次条件匹配判断,这多次判断中的任何一项在匹配成功后都会执行相应的预设命令,相当于口语的“如果……那么……如果……那么……”。if条件语句的多分支结构是工作中最常使用的一种条件判断结构,尽管相对复杂但是更加灵活。

案例:

[root@localhost ~]# vim a.sh

#!/bin/bash

if [ "${1}" == "hello" ]; then

echo "Hello, how are you ?"

elif [ "${1}" == "" ]; then

echo "You MUST input parameters, ex> {${0} someword}"

else

echo "The only parameter is 'hello', ex> {${0} hello}"

fi

[root@localhost ~]# sh a.sh \\可以看到必须加参数才能执行

You MUST input parameters, ex> {a.sh someword}

[root@localhost ~]# sh a.sh hello

Hello, how are you ?

利用if... then:网络状态

[root@localhost ~]# vim netstat.sh

#!/bin/bash

echo "Now, I will detect your Linux server's services!"

echo -e "The www, ftp, ssh, and mail(smtp) will be detect! \n"

testfile=/dev/shm/netstat_checking.txt

netstat -tuln > ${testfile}

testing=$(grep ":80 " ${testfile}) \\侦测80端口是否存在

if [ "${testing}" != "" ]; then

echo "WWW is running in your system."

fi

testing=$(grep ":22 " ${testfile}) \\侦测22端口是否存在

if [ "${testing}" != "" ]; then

echo "SSH is running in your system."

fi

testing=$(grep ":21 " ${testfile}) \\侦测21端口是否存在

if [ "${testing}" != "" ]; then

echo "FTP is running in your system."

fi

testing=$(grep ":25 " ${testfile})

if [ "${testing}" != "" ]; then

echo "Mail is running in your system."

fi

[root@localhost ~]# sh netstat.sh

Now, I will detect your Linux server's services!

The www, ftp, ssh, and mail(smtp) will be detect!

SSH is running in your system. \\看到ssh正在系统中运行

Mail is running in your system. \\邮件服务正在系统中运行

for条件循环语句

for循环语句允许脚本一次性读取多个信息,然后逐一对信息进行操作处理,当要处理的数据有范围时,使用for循环语句再适合不过了。

for...do...done(固定循环)

案例:

假设我有三种动物,分别是 dog, cat, elephant 三种,我想每一行都输出这样:“There are dogs...”之类的字样,则可以:

[root@localhost ~]# vim w.sh

for animal in dog cat elephant

do

echo "There are ${animal}s.... "

done

[root@localhost ~]# sh w.sh

There are dogs....

There are cats....

There are elephants....

while条件循环语句

while条件循环语句是一种让脚本根据某些条件来重复执行命令的语句,它的循环结构往往在执行前并不确定最终执行的次数,完全不同于for循环语句中有目标、有范围的使用场景。while循环语句通过判断条件测试的真假来决定是否继续执行命令,若条件为真就继续执行,为假就结束循环。

while... do...done,until...do...done(不定循环)

While:当满足后面条件时才进行循环

Until:当不满足后面条件时才进行循环

案例:

假设我要让使用者输入 yes 或者是 YES 才结束程序的执行,否则就一直进行告知使用者输入字串。

[root@localhost ~]# vim s.sh

#!/bin/bash

while [ "${yn}" != "yes" -a "${yn}" != "YES" ]

do

read -p "Please input yes/YES to stop this program: " yn

done

echo "OK! you input the correct answer."

[root@localhost ~]# sh s.sh

Please input yes/YES to stop this program: asd

Please input yes/YES to stop this program: asd

Please input yes/YES to stop this program: YES

OK! you input the correct answer.

case条件测试语句

case语句是在多个范围内匹配数据,若匹配成功则执行相关命令并结束整个条件测试;而如果数据不在所列出的范围内,则会去执行星号(*)中所定义的默认命令。

利用case .... esac判断

[root@localhost ~]# vim aa.sh

#!/bin/bash

case ${1} in

"hello")

echo "Hello, how are you ?"

;;

"")

echo "You MUST input parameters, ex> {${0} someword}"

;;

*)

echo "Usage ${0} {hello}"

;;

esac

[root@localhost ~]# sh aa.sh

You MUST input parameters, ex> {aa.sh someword}

[root@localhost ~]# sh aa.sh hello

Hello, how are you ?

一般来说,使用“ case $变量 in ”这个语法中,当中的那个“ $变量 ”大致有两种取得的方式:

直接下达式:例如上面提到的,利用“ script.sh variable ” 的方式来直接给予 $1 这个变量的内容,这也是在 /etc/init.d 目录下大多数程序的设计方式。

互动式:通过 read 这个指令来让使用者输入变量的内容。

让使用者能够输入 one, two, three ,并且将使用者的变量显示到屏幕上,如果不是 one, two, three 时,就告知使用者仅有这三种选择。

[root@localhost ~]# vim bb.sh

#!/bin/bash

echo "This program will print your selection !"

#read -p "Input your choice: " choice

#case ${choice} in

case ${1} in

"one")

echo "Your choice is ONE"

;; "two") echo "Your choice is TWO" ;;

"three")

echo "Your choice is THREE"

;;

*)

echo "Usage ${0} {one|two|three}"

;;

esac

[root@localhost ~]# sh bb.sh

This program will print your selection !

Usage bb.sh {one|two|three}

[root@localhost ~]# sh bb.sh one

This program will print your selection !

Your choice is ONE

[root@localhost ~]# sh bb.sh two

This program will print your selection !

Your choice is TWO

函数

函数的定义

在shell 中有两种定义函数的语法格式,分别为:

函数名()

{

命令序列

}

或者:

function 函数名()     /function 可以不写

{

命令序列

}

函数定义好后,用户可以在shell 中直接调用,调用时不用带上()

调用语法

函数名   参数1   参数2 ....

函数中的变量

均为全局变量,没有局部变量

函数的调用

可以传递参数,在函数中用$1,$2, $3...来引用传递的参数。

还用上面的案例:用函数调用实现

[root@localhost ~]# vim cc.sh

#!/bin/bash

function printit(){

echo -n "Your choice is "

}

echo "This program will print your selection !"

case ${1} in

"one")

printit; echo ${1} | tr 'a-z' 'A-Z' \\将参数的大小写转换

;; "two")

printit; echo ${1} | tr 'a-z' 'A-Z'

;;

"three")

printit; echo ${1} | tr 'a-z' 'A-Z'

;;

*)

echo "Usage ${0} {one|two|three}"

;;

esac

[root@localhost ~]# sh cc.sh

This program will print your selection !

Usage cc.sh {one|two|three}

[root@localhost ~]# sh cc.sh one

This program will print your selection !

Your choice is ONE

[root@localhost ~]# sh cc.sh two

This program will print your selection !

Your choice is TWO

Shell脚本的追踪与debug

sh执行的选项与参数:

-n :不要执行script(脚本),仅查询语法的问题

-v :在执行script前,先将脚本的内容输出到屏幕上

-x :将使用到的脚本内容显示到屏幕上,

案例:

[root@localhost ~]# sh -n aa.sh \\不报错证明正常

[root@localhost ~]# sh -v aa.sh \\输出到屏幕上

#!/bin/bash

case ${1} in

"hello")

echo "Hello, how are you ?"

;;

"")

echo "You MUST input parameters, ex> {${0} someword}"

;;

*)

echo "Usage ${0} {hello}"

;;

esac

You MUST input parameters, ex> {aa.sh someword}

[root@localhost ~]# sh -x cc.sh \\可使用的输出屏幕上

+ echo 'This program will print your selection !'

This program will print your selection !

+ case ${1} in

+ echo 'Usage cc.sh {one|two|three}'

Usage cc.sh {one|two|three}

怎么编写Linux脚本循环语句,shell脚本及常用循环语句相关推荐

  1. Linux命令行与shell脚本编程大全:第2版

    <Linux命令行与shell脚本编程大全:第2版> 基本信息 作者: (美)布卢姆(Blum,R.) 布雷斯纳汉(Bresnahan.C.) [作译者介绍] 译者: 武海峰 丛书名: 图 ...

  2. 《Linux命令行与Shell脚本编程大全第2版.布卢姆》pdf

    下载地址:网盘下载 内容简介  · · · · · · 本书是一本关于Linux 命令行与shell 脚本编程的全面教程.全书分为四部分:第一部分介绍Linuxshell 命令行:第二部分介绍shel ...

  3. 《Linux命令行与shell脚本大全》笔记

    初识Linux Shell 什么是Linux Linux可划分为以下四部分: Linux内核 GNU工具 图形化桌面环境 应用软件 深入探究Linux内核 内核主要负责以下四种功能: 系统内存管理 软 ...

  4. 【Linux】《Linux命令行与shell脚本编程大全 (第4版) 》笔记-汇总 ( Chapter17-ChapterB )

    十七.创建函数 bash shell 提供了用户自定义函数功能,可以将 shell 脚本代码放入函数中封装起来. 函数是一个脚本代码块,你可以为其命名并在脚本中的任何位置重用它.每当需要在脚本中使用该 ...

  5. 【2018深信服 醒狮计划】《Linux命令行与Shell脚本编程大全》学习笔记

    2018深信服"醒狮计划"笔记 第3周(5.02-5.13) 课程 必修 选修 基本要求 Shell编程 <Linux命令行与Shell脚本编程大全> <Perl ...

  6. linux运维自动化脚本,linux运维自动化shell脚本小工具

    linux运维shell 脚本小工具,如要分享此文章,请注明文章出处,以下脚本仅供参考,若放置在服务器上出错,后果请自负 1.检测cpu剩余百分比 #!/bin/bash #Inspect CPU # ...

  7. 《Linux命令行与shell脚本编程大全》笔记一

    第一章 初始 Linux shell Linux内核主要四种功能: 1.系统内存管理 2.软件程序管理 3.硬件设备管理 4.文件系统管理 shell:交互工具. 第三章 基本的bash shell ...

  8. linux csh 安装,linux安装gcc的shell脚本

    原标题:linux安装gcc的shell脚本 GCC是GUN Compiler Collection的简称,除了编译程序之外,它还含其他相关工具,它能把易于人类使用的高级语言编写的源代码构建成计算机能 ...

  9. linux 命令行与shell脚本编程大全

    linux 命令行与shell脚本编程大全 第一章 Linux LiveCD就是从cd读取的系统,由于没法将数据写入到cd,所以一旦重启,之前操作过后的一切数据都会丢失. 第二章 第三章 1.man手 ...

  10. linux脚本求命令行上整数和,《Linux命令行与shell脚本编程大全》 第二十二章 学习札记...

    <Linux命令行与shell脚本编程大全> 第二十二章 学习笔记 第二十二章:使用其他shell 什么是dash shell Debian的dash shell是ash shell的直系 ...

最新文章

  1. 【AI】caffe使用步骤(一):将标注数据生成lmdb或leveldb
  2. c# 线程间操作无效: 从不是创建控件“”的线程访问它,用托管来解决
  3. 如何获取NumPy数组中N个最大值的索引?
  4. c 是泛型程序设计语言,c ++中的“泛型编程”是什么意思?
  5. mysql 增量备份_MySQL增量备份与恢复(增量备份概述、特点,断点恢复实操)
  6. Linux重定向和管道的基础学习
  7. 电力拖动计算机控制系统讲什么,电力拖动自动控制系统
  8. 【神经网络】神经元模型和感知器
  9. 远程办公——如何在外远程控制家里/公司的电脑,利用cpolar内网穿透
  10. 8、OpenCV调整图像对比度和亮度
  11. iOS远程推送--APNs详解
  12. 库存商品管理机试题(JSP)——试题讲解
  13. 【NLP】(task8)Transformers完成抽取式问答+多选问答任务(更新ing)
  14. 问卷调查的数据分析怎么做
  15. The Fewest Coins(多重背包+完全背包)
  16. Windows 修改MAC地址
  17. info testing mysql_sqlmap新手注入
  18. 解决报错“RuntimeError - [Xcodeproj] Unknown object version.”
  19. 网线每根的含义以及类别和距离传输问题
  20. 我的Linux(ubuntu)自学笔记分享

热门文章

  1. nyoj711zznu1624 最舒适的路线(第六届河南省程序设计大赛 广搜)
  2. 图神经网络相似度计算
  3. 京东面试官问哭的秒杀系统考点
  4. 程序流程图是什么?基本流程图讲解
  5. txt转换pdf格式转换器的操作步骤
  6. 【深度学习】 NLP和神经网络表示
  7. 隐式马尔科夫模型(HMM)
  8. 关联规则算法在游戏行业中的应用
  9. 为您审核的30多个Web工具和服务
  10. 蓝桥杯(十六进制转八进制)