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/bashecho -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/bashread -p "Please input your first name: " firstnameread -p "Please input your last name: " lastnameecho -e "\nYour full name is: ${firstname} ${lastname}"[root@localhost ~]# sh b.sh Please input your first name: xPlease input your last name: aYour full name is: x a随日期变化:利用date进行件的创建
[root@localhost ~]# vim x.sh#!/bin/bashecho -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/bashecho -e "You SHOULD input 2 numbers, I will multiplying them! \n"read -p "first number: " firstnuread -p "second number: " secnutotal=$((${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: 2second number: 3The result of 2 x 3 is ==> 6利用test指令的测试功能

三.循环语句
if条件测试语句
if条件测试语句可以让脚本根据实际情况自动执行相应的命令。从技术角度来讲,if语句分为单分支结构、双分支结构、多分支结构;其复杂度随着灵活度一起逐级上升。
1.if条件语句的单分支结构由if、then、fi关键词组成,而且只在条件成立后才执行预设的命令,相当于口语的"如果……那么……"。单分支的if语句属于最简单的一种条件判断结构。

案例:
[root@localhost ~]# vim x.sh #!/bin/bashread -p "Please input (Y/N): " ynif [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; thenecho "OK, continue" exit 0fiif [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; thenecho "Oh, interrupt!" exit 0fiecho "I don't know what your choice is" && exit 0[root@localhost ~]# sh x.sh Please input (Y/N): YOK, continue[root@localhost ~]# sh x.sh Please input (Y/N): NOh, interrupt![root@localhost ~]# sh x.sh Please input (Y/N): asdI don't know what your choice is2.if条件语句的双分支结构由if、then、else、fi关键词组成,它进行一次条件匹配判断,如果与条件匹配,则去执行相应的预设命令;反之则去执行不匹配时的预设命令,相当于口语的"如果……那么……或者……那么……"。if条件语句的双分支结构也是一种很简单的判断结构。
https://s1.51cto.com/images/blog/201809/17/e6093221273e0d416b0ee944c5e318c4.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
还用上面的案例:
[root@localhost ~]# vim x.sh#!/bin/bashread -p "Please input (Y/N): " ynif [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; thenecho "OK, continue"elif [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; thenecho "Oh, interrupt!"elseecho "I don't know what your choice is"fi[root@localhost ~]# sh x.sh Please input (Y/N): YOK, continue3.if条件语句的多分支结构由if、then、else、elif、fi关键词组成,它进行多次条件匹配判断,这多次判断中的任何一项在匹配成功后都会执行相应的预设命令,相当于口语的"如果……那么……如果……那么……"。if条件语句的多分支结构是工作中最常使用的一种条件判断结构,尽管相对复杂但是更加灵活。
案例:
[root@localhost ~]# vim a.sh#!/bin/bashif [ "${1}" == "hello" ]; thenecho "Hello, how are you ?"elif [ "${1}" == "" ]; thenecho "You MUST input parameters, ex> {${0} someword}"elseecho "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 helloHello, how are you ?利用if... then:网络状态
[root@localhost ~]# vim netstat.sh#!/bin/bashecho "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.txtnetstat -tuln > ${testfile}testing=$(grep ":80 " ${testfile}) \\侦测80端口是否存在if [ "${testing}" != "" ]; thenecho "WWW is running in your system."fitesting=$(grep ":22 " ${testfile}) \\侦测22端口是否存在if [ "${testing}" != "" ]; thenecho "SSH is running in your system."fitesting=$(grep ":21 " ${testfile}) \\侦测21端口是否存在if [ "${testing}" != "" ]; thenecho "FTP is running in your system."fitesting=$(grep ":25 " ${testfile})if [ "${testing}" != "" ]; thenecho "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.shfor animal in dog cat elephantdoecho "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/bashwhile [ "${yn}" != "yes" -a "${yn}" != "YES" ]doread -p "Please input yes/YES to stop this program: " yndoneecho "OK! you input the correct answer."[root@localhost ~]# sh s.sh Please input yes/YES to stop this program: asdPlease input yes/YES to stop this program: asdPlease input yes/YES to stop this program: YESOK! you input the correct answer.case条件测试语句
case语句是在多个范围内匹配数据,若匹配成功则执行相关命令并结束整个条件测试;而如果数据不在所列出的范围内,则会去执行星号(*)中所定义的默认命令。
利用case .... esac判断
[root@localhost ~]# vim aa.sh#!/bin/bashcase ${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 helloHello, 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/bashecho "This program will print your selection !"#read -p "Input your choice: " choice#case ${choice} incase ${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 oneThis program will print your selection !Your choice is ONE[root@localhost ~]# sh bb.sh twoThis program will print your selection !Your choice is TWO函数
函数的定义
在shell 中有两种定义函数的语法格式,分别为:
函数名()
{
命令序列
}
或者:
function 函数名() /function 可以不写
{
命令序列
}
函数定义好后,用户可以在shell 中直接调用,调用时不用带上()
调用语法 函数名 参数1 参数2 .... 函数中的变量 均为全局变量,没有局部变量 函数的调用 可以传递参数,在函数中用$1,$2, $3...来引用传递的参数。
还用上面的案例:用函数调用实现
[root@localhost ~]# vim cc.sh#!/bin/bashfunction 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 oneThis program will print your selection !Your choice is ONE[root@localhost ~]# sh cc.sh twoThis program will print your selection !Your choice is TWOShell脚本的追踪与debug
sh执行的选项与参数:-n :不要执行script(脚本),仅查询语法的问题-v :在执行script前,先将脚本的内容输出到屏幕上-x :将使用到的脚本内容显示到屏幕上,
案例:
[root@localhost ~]# sh -n aa.sh \\不报错证明正常[root@localhost ~]# sh -v aa.sh \\输出到屏幕上#!/bin/bashcase ${1} in"hello")echo "Hello, how are you ?";;"")echo "You MUST input parameters, ex> {${0} someword}" ;;*)echo "Usage ${0} {hello}" ;;esacYou 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}看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。