Shell学习笔记

一、什么是Shell脚本

Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。

Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内核的服务。

Ken Thompson 的 sh 是第一种 Unix Shell,Windows Explorer 是一个典型的图形界面 Shell。

1、Shell环境

Shell 编程跟 JavaScript、php 编程一样,只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。

Linux 的 Shell 种类众多,常见的有:

  • Bourne Shell(/usr/bin/sh或/bin/sh)
  • Bourne Again Shell(/bin/bash)
  • C Shell(/usr/bin/csh)
  • K Shell(/usr/bin/ksh)
  • Shell for Root(/sbin/sh)
  • ......

本教程关注的是 Bash,也就是 Bourne Again Shell,由于易用和免费,Bash 在日常工作中被广泛使用。同时,Bash 也是大多数Linux 系统默认的 Shell。

用法:Shebang通常出现在类Unix系统的脚本中第一行,作为前两个字符。在Shebang之后,可以有一个或数个空白字符,后接解释器的绝对路径,用于指明执行这个脚本文件的解释器。

#! /bin/bash

echo "hello shell"

Shebang注意事项:

#! 必须连接在一起
#! 一句必须在文件的最开始,第一行
# 开头的语句一般情况下会被当成注释而忽略,所以Shebang 对文件的内容是没有影响的
#! 开头的一行会设置解释器运行环境

2、bash特性

 bash基础特性:

● bash是一 个命令处理器,运行在文本窗口中,并能执行用户直接输入的命令;
● bash还能从文件中读取linxu命令,称之为脚本;
● bash支持通配符、 管道、命令替换、条件判断等逻辑控制语句;

bash七大特性:

  • ⽂件路径tab键补全
  • 命令补全
  • 快捷键ctrl + a,e,u,k,l
  • 通配符
  • 命令历史
  • 命令别名
  • 命令⾏展开

编辑快捷键

  1. Ctrl + a :移到命令行首
  2. Ctrl + e :移到命令行尾
  3. Ctrl + f :按字符前移(右向)
  4. Ctrl + b :按字符后移(左向)
  5. Alt + f :按单词前移(右向)
  6. Alt + b :按单词后移(左向)
  7. Ctrl + xx:在命令行首和光标之间移动
  8. Ctrl + u :从光标处删除至命令行首
  9. Ctrl + k :从光标处删除至命令行尾
  10. Ctrl + w :从光标处删除至字首
  11. Alt + d :从光标处删除至字尾
  12. Ctrl + d :删除光标处的字符
  13. Ctrl + h :删除光标前的字符
  14. Ctrl + y :粘贴至光标后
  15. Alt + c :从光标处更改为首字母大写的单词
  16. Alt + u :从光标处更改为全部大写的单词
  17. Alt + l :从光标处更改为全部小写的单词
  18. Ctrl + t :交换光标处和之前的字符
  19. Alt + t :交换光标处和之前的单词
  20. Alt + Backspace:与 Ctrl + w 相同类似,分隔符有些差别

重新执行快捷键

  1. Ctrl + r:逆向搜索命令历史
  2. Ctrl + g:从历史搜索模式退出
  3. Ctrl + p:历史中的上一条命令
  4. Ctrl + n:历史中的下一条命令
  5. Alt + .:使用上一条命令的最后一个参数

控制快捷键:

  1. Ctrl + l:清屏
  2. Ctrl + o:执行当前命令,并选择上一条命令
  3. Ctrl + s:阻止屏幕输出
  4. Ctrl + q:允许屏幕输出
  5. Ctrl + c:终止命令
  6. Ctrl + z:挂起命令

Bang (!) 命令:

  1. !!:执行上一条命令
  2. !blah:执行最近的以 blah 开头的命令,如 !ls
  3. !blah:p:仅打印输出,而不执行
  4. !$:上一条命令的最后一个参数,与 Alt + . 相同
  5. !$:p:打印输出 !$ 的内容
  6. !*:上一条命令的所有参数
  7. !*:p:打印输出 !* 的内容
  8. ^blah:删除上一条命令中的 blah
  9. ^blah^foo:将上一条命令中的 blah 替换为 foo
  10. ^blah^foo^:将上一条命令中所有的 blah 都替换为 foo

关于bash历史记录的简单用法

[root@192 shell]# history                 #命令,查看历史命令记录
    1  set +o history;
    2  cd /
    3  cd user
    4  cd home/
    5  ls
    6  mkdir tar
    7  ls
    8  ll
    9  cd tar/
[root@192 shell]# echo $HISTSIZE           #查看历史记录行数,最多能看到1000行
1000
[root@192 shell]# vim ~/.bash_history      #~/.bash_history里存放用户执行的历史命令
[root@192 shell]# echo $HISTFILE           #$HISTFILE可以看到文件的地址
/root/.bash_history
[root@192 shell]# history -c               #-c:清空内存中命令历史
[root@192 shell]# history 
    1  history      
[root@192 shell]# history -r ~/.bash_history    #-r:从⽂件中恢复历史命令
[root@192 shell]# history
    1  history 
    2  history -r ~/.bash_history
    3  set +o history;
    4  cd /
    5  cd user
    6  cd home/
    7  ls
    8  mkdir tar
    9  ls

调用历史记录的用法

[root@192 shell]# history            #查看历史记录
    1  ls
    2  history 
[root@192 shell]# !1                 #通过!历史id执行历史记录
ls
Hannahx2.txt  Hannahx3.txt  Hannahx4.txt  Hannahx5.txt  Hannahxhannah.txt  HannahxHannahx1.txt  Hannahxping.txt  hello_shell.sh
[root@192 shell]# !!                 #通过!!执行上次执行的记录
ls
Hannahx2.txt  Hannahx3.txt  Hannahx4.txt  Hannahx5.txt  Hannahxhannah.txt  HannahxHannahx1.txt  Hannahxping.txt  hello_shell.sh

二、Shell变量

变量是暂时存储数据的地⽅,是⼀种数据标记(房间号,标记了客⼈所在的位置),数据存储在内容空间,通过调⽤正确的变量名字,即可取出对应的值。

Shell命名规则: 

名称定义要做到⻅名知意,切按照规则来,切不得引⽤保留关键字(help检查保留字)

  • 只能包含数字、字⺟、下划线
  • 不能以数字开头
  • 不能⽤标点符号
  • 变量名严格区分⼤⼩写

1、系统变量

        系统变量区分为两类:

        系统变量:也称为全局变量,针对当前shell以及其任意⼦进程,环境变量也分⾃定义 、内置两种环境变量

        局部变量:针对在 shell函数 或是shell脚本中定义

变量常用命令:

[root@192 shell]# set            #输出所有变量,包括全局变量、局部变量
[root@192 shell]# env            #只显示局部变量
[root@192 shell]# declare        #输出所有变量,和set类似
[root@192 shell]# export         #显示和设置环境变量
[root@192 shell]# unset 变量名    #删除变量或函数
[root@192 shell]# readyonly    变量名=值    #设置只读变量,不能重新赋值

2、自定义变量 

        变量赋值:变量名=变量值

        变量引用:echo $变量名

        

        echo -n 表示不换行输出
        使用echo -e输出转义字符
        转义字符:
        \c 不换行输出,在”\c”后面不存在字符的情况下,作用相当于echo -n
        \n 换行
        \t 转义后表示插入tab,即制表符
        \b 退格
        \f 换行,光标仍停留在原处

[root@192 shell]# name='Hannahx'        #单引号只识别为字符串
[root@192 shell]# echo $name 
Hannahx
[root@192 shell]# name="${age}"         #双引号可以识别特殊符号
[root@192 shell]# echo $name 
aabaaaaccdd
[root@192 shell]# name=`ls -a`          #反斜杠可以识别命令
[root@192 shell]# echo $name 
Hannahx2.txt Hannahx3.txt Hannahx4.txt Hannahx5.txt Hannahxhannah.txt HannahxHannahx1.txt Hannahxping.txt hello_shell.sh
[root@192 shell]# 

 3、特殊变量

        shell的特殊变量可以用在如脚本、函数传递时使用;

特殊的参数变量:

$0:获取shell脚本文件名,以及脚本路径

$n:获取shell脚本的第几个参数,如$1获取shell脚本后带的第一个参数

$#:获取shell脚本执行后的参数个数

$*:获取shell脚本执行后的所有参数,不管后面多少个参数是作为一整个

$@:获取shell脚本执行后的所有参数,所接受的参数以空格隔开,为独立的每个参数

特殊的状态变量:

$?:返回上一次执行结果的状态,0成功,非0失败

$$:返回当前shell脚本的进程号

$!:返回上一次后台进程的PID

$_:返回上次执行命令的最后一个参数

特殊的赋值变量:

:-         ${string:-position}        如果string不为空,将string的值返回。如果string为空,将position返回

:=        ${string:=position}       如果string不为空,将string的值返回。如果string为空,将position返回并修改string的值为position

:?        ${string:?position}       如果string不为空,将string的值返回。如果string为空,则报错

:+        ${string:+position}       如果string不为空,将position的值返回。如果string为空,则什么都不做

————————————————————————————————:-————————————————————————————————————
[root@192 shell]# echo $name                     #name不为空
name
[root@192 shell]# echo $age                      #age为空

[root@192 shell]# result1=${name:-HannahXx}      #如果name不为空,将name返回给result1
[root@192 shell]# echo $name 
name
[root@192 shell]# echo $result1
name
[root@192 shell]# result2=${age:-HannahXx}       #如果age为空,将HannahXx返回给result2
[root@192 shell]# echo $age

[root@192 shell]# echo $result2
HannahXx

————————————————————————————————:=————————————————————————————————————
[root@192 shell]# echo $name
name
[root@192 shell]# echo $age

[root@192 shell]# result7=${name:=HannahXx}
[root@192 shell]# echo $name 
name
[root@192 shell]# echo $result7
name
[root@192 shell]# result8=${age:=HannahXx}
[root@192 shell]# echo $age
HannahXx
[root@192 shell]# echo $result8
HannahXx
[root@192 shell]# 

————————————————————————————————:+————————————————————————————————————
[root@192 shell]# echo $name
name
[root@192 shell]# echo $age

[root@192 shell]# result3=${name:+HannahXx}
[root@192 shell]# echo $name
name
[root@192 shell]# echo $result3
HannahXx
[root@192 shell]# result4=${age:+HannahXx}
[root@192 shell]# echo $age

[root@192 shell]# echo $result4

[root@192 shell]# 

————————————————————————————————:?————————————————————————————————————
[root@192 shell]# echo $name
name
[root@192 shell]# echo $age

[root@192 shell]# result5=${name:?HannahXx}
[root@192 shell]# echo $name
name
[root@192 shell]# echo $result5
name
[root@192 shell]# result6=${age:?HannahXx}
-bash: age: HannahXx
[root@192 shell]# echo $age

[root@192 shell]# echo $result6

[root@192 shell]# 

4、字符操作

${#string}                              $string的长度
${string:position}                   在$string中, 从位置$position开始提取子串
${string:position:length}        在$string中, 从位置$position开始提取长度为$length的子串
 
${string#substring}        从变量$string的开头, 删除最短匹配$substring的子串
${string##substring}      从变量$string的开头, 删除最长匹配$substring的子串
${string%substring}       从变量$string的结尾, 删除最短匹配$substring的子串
${string%%substring}    从变量$string的结尾, 删除最长匹配$substring的子串
      
${string/substring/replacement}        使用$replacement, 来代替第一个匹配的$substring
${string//substring/replacement}       使用$replacement, 代替所有匹配的$substring
${string/#substring/replacement}      如果$string的前缀匹配$substring, 那么就用$replacement来代替匹配到的$substring
${string/%substring/replacement}     如果$string的后缀匹配$substring, 那么就用$replacement来代替匹配到的$substring

[root@192 shell]# name='abc123abcABCabc'    #自定义变量name
[root@192 shell]# echo $name                #echo引用变量
abc123abcABCabc
[root@192 shell]# echo ${#name}             #打印变量长度
15
[root@192 shell]# echo ${name:4}            #索引从0开始,从4号位开始截取变量
23abcABCabc
[root@192 shell]# echo ${name:4:4}          #从4号位截取往后截取4位
23ab
[root@192 shell]# echo ${name#a*a}          #从前面开始,截取第一次出现a*a的字符,*表示通配符
bcABCabc
[root@192 shell]# echo ${name##a*a}         #从前面开始,截取最后一次出现a*a的字符
bc
[root@192 shell]# echo ${name%c*c}          #从后面开始,截取第一次出现c*c的字符
abc123ab
[root@192 shell]# echo ${name%%c*c}         #从后面开始,截取最后一次出现c*c的字符
ab
[root@192 shell]# echo ${name/abc/ABC}      #从前面开始,用ABC替换第一次出现abc的位置
ABC123abcABCabc
[root@192 shell]# echo ${name//abc/ABC}     #从前面开始,用ABC替换所有出现abc的位置
ABC123ABCABCABC
[root@192 shell]# echo ${name/#ABC/abc}     #从前面开始,如果是ABC开头,替换成abc
abc123abcABCabc
[root@192 shell]# echo ${name/%abc/ABC}     #从后面开始,如果结尾是abc,替换成ABC
abc123abcABCABC

 三、shell命令

shell命令可分为两种,一种为内嵌命令或内置命令,另一种为外部命令或外置命令

        内置命令:在系统启动时就加载到内存中,常驻内存中,执行效率很高,但是占用资源

        外置命令:在系统中用户自行下载的程序的执行命令,执行时需要从硬盘中去读取程序文件,再加载到内存中,执行效率低,占用资源少

检查内置、外置命令的方式:

  1. type
  2. compgen -b
[root@192 shell]# type cd        #查看cd命令是否为内置命令
cd 是 shell 内嵌
[root@192 shell]# type ls        #查看ls命令是否为内置命令
ls 是 `ls --color=auto' 的别名    #不是内置命令
[root@192 shell]# which ls       #查看ls命令程序在哪
alias ls='ls --color=auto'
        /usr/bin/ls
[root@192 shell]# compgen -b     #查看所有的内置命令
.
:
[
alias
bg
bind
break
builtin
caller
cd
command
compgen
complete
compopt
continue
declare
dirs
disown
echo
enable
eval
exec
exit
export
false
fc
fg
getopts
hash
help
history
jobs
kill
let
local
logout
mapfile
popd
printf
pushd
pwd
read
readarray
readonly
return
set
shift
shopt
source
suspend
test
times
trap
true
type
typeset
ulimit
umask
unalias
unset
wait
[root@192 shell]# 

四、算术运算

1、shell中支持的算术

算术运算符说明/含义
+、-加法(或正号)、减法(或负号)
*、/、%乘法、除法、取余(取模)
**幂运算
++、–自增和自减,可以放在变量的前面也可以放在变量的后面
!、&&、||逻辑非(取反)、逻辑与(and)、逻辑或(or)
<、<=、>、>=比较符号(小于、小于等于、大于、大于等于)
==、!=、=比较符号(相等、不相等;对于字符串,= 也可以表示相当于)
<<、>>向左移位、向右移位
~、|、 &、^按位取反、按位或、按位与、按位异或
=、+=、-=、*=、/=、%=赋值运算符,例如 a+=1 相当于 a=a+1,a-=1 相当于 a=a-1

2、shell中数学计算方式

运算操作符说明/含义
(( ))用于整数运算,效率很高,推荐使用
let用于整数运算,和 (()) 类似。
$[]用于整数运算,不如 (()) 灵活。
expr可用于整数运算,也可以处理字符串。比较麻烦,需要注意各种细节,不推荐使用。
bcLinux下的一个计算器程序,可以处理整数和小数。Shell 本身只支持整数运算,想计算小数就得使用 bc 这个外部的计算器。
--------------------------------(())----------------------------------
[root@192 shell]# age=18
[root@192 shell]# echo $age 
18
[root@192 shell]# echo  $((age+5))
23
[root@192 shell]# echo $((age-5))
13
[root@192 shell]# echo $((age/2))
9
[root@192 shell]# echo #((age*2))

[root@192 shell]# echo $((age*2))
36
[root@192 shell]# echo $age
18
[root@192 shell]# echo $((`seq -s "+" 100`))    #计算0到100的和
5050
[root@192 shell]# 

--------------------------------let----------------------------------
[root@192 shell]# echo $age 
18
[root@192 shell]# let num=age+3
[root@192 shell]# echo $num
21
[root@192 shell]# let num=age/3
[root@192 shell]# echo $num
6
[root@192 shell]# let num=age*3
[root@192 shell]# echo $num
54
[root@192 shell]# 

--------------------------------expr----------------------------------
[root@192 shell]# echo $age 
18
[root@192 shell]# expr $age - 1
17
[root@192 shell]# expr $age + 3
21
[root@192 shell]# expr $age * 3    #expr语法错误,需要将特殊字符转义
expr: 语法错误
[root@192 shell]# expr $age \* 3
54
[root@192 shell]# expr $age \ 3    #expr语法错误,需要将特殊字符转义
expr: 语法错误
[root@192 shell]# expr $age \/ 3
6
[root@192 shell]# expr length ahabfnajbgakjbgakbga    #expr计算长度的方法length
20
[root@192 shell]# expr HannahXx.jpg ":" ".*\.png"     #expr模式匹配,匹配照片是否后缀为png
0
[root@192 shell]# expr HannahXx.jpg ":" ".*\.jpg"     #匹配上返回出现的索引位置
12
[root@192 shell]# seq -s " + " 100 | xargs expr       #计算0到100的和
5050
[root@192 shell]# 

--------------------------------bc----------------------------------
[root@192 shell]# bc            #bc计算器
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
1*2        #算术表达式
2          #结果
8*8        #算术表达式
64         #结果
66/6
11
2+4
6
8%2
0
^C
(interrupt) Exiting bc.
[root@192 shell]# echo {0..100} |tr " " "+"        #打印0到100相加的算术表达式
0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100
[root@192 shell]# echo {0..100} |tr " " "+" | bc    #bc结合管道符计算0到100的和
5050
[root@192 shell]# seq -s "+" 100            #打印0到100相加的算术表达式
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100
[root@192 shell]# seq -s "+" 100 | bc    #bc结合管道符计算0到100的和
5050

--------------------------------awk----------------------------------

[root@192 shell]# echo "8.0 9.0" | awk '{print ($1+$2)}'
17
[root@192 shell]# echo "8.2 9.0" | awk '{print ($1-$2)}'
-0.8
[root@192 shell]# echo "8.2 9.0" | awk '{print ($1*$2)}'
73.8
[root@192 shell]# echo "8.2 9.0" | awk '{print ($1/$2)}'
0.911111

--------------------------------$[表达式]----------------------------------
[root@192 shell]# num=5
[root@192 shell]# res=$[num+5]
[root@192 shell]# echo $res
10
[root@192 shell]# res=$[num*10]
[root@192 shell]# echo $res
50
[root@192 shell]# 

五、逻辑判断

  1. 把字符串当成整型进行比较,由于abcd等字符对不上0123当程序尝试去转成二进制时无法完成转换,所以用于数值比较的运算不能用于字符串比较;但是把整型当成字符串进行比较,0123这些数值完全可以转成ASCII码而且原本两个整型相等则变成ASCII码还是相等、不等的还是不等,所以可用于字符串的比较也可用于整型的比较

  2. if语句中,数值比较的写法是if [ $var1 -ge $var2 ];字符串比较的写法是if [ "$var1" != "$var2" ],其中加双引号只是兼容$var2处为空的情况

  3. 在各种运算中,test命令的运算和中括号是等效的

  4. 赋值时等号两边没空格,比较或测试时运算符两边都要有空格

逻辑运算方式:

  • test
  • [表达式]

1、运算符

1.1、数值的比较

参数说明
-eq等于则为真
-ne不等于则为真
-gt大于则为真
-ge大于等于则为真
-lt小于则为真
-le小于等于则为真

1.2、字符串的比较

参数说明
==两边相等则为真
!=两边不相等则为真
=~前边变量包括后边变量则为真

1.3、字符串的测试运算

参数说明
-z字符串长度为0则为真
-n字符串长度不为0则为真

1.4、 文件测试运算

参数说明
-e 文件名如果文件存在则为真
-r 文件名如果文件存在且可读则为真
-w 文件名如果文件存在且可写则为真
-x 文件名如果文件存在且可执行则为真
-s 文件名如果文件存在且至少有一个字符则为真
-d 文件名如果文件存在且为目录则为真
-f 文件名如果文件存在且为普通文件则为真
-c 文件名如果文件存在且为字符型特殊文件则为真
-b 文件名如果文件存在且为块特殊文件则为真

1.5、逻辑运算

参数说明
&&或者-a
||或者-o
!
[root@192 shell]# ls
hello_shell.sh
[root@192 shell]# test -f hello_shell.sh && echo "$1 是一个文件" || echo ”$1 不是一个文件“    #判断hello_shell.sh是否为一个文件
abc123abcABCabc 是一个文件
[root@192 shell]# test 1>0 && echo 'ture' || echo 'false'
false
[root@192 shell]# test 1 -le 0 && echo 'ture' || echo 'false'    #test判断
false
[root@192 shell]# test 1 -gt 0 && echo 'ture' || echo 'false'
ture
[root@192 shell]# [ 1 -gt 0 ] && echo 'ture' || echo 'false'    #[]表达式判断
ture
[root@192 shell]# 

 2、流程控制

2.1、if判断

2.1.1、单分支语句结构

if [ 条件表达式 ]

then
        指令
fi

2.1.2、双分支语句结构

if [ 条件表达式 ]

then 
        指令一 
else 
        指令二 
fi 

2.1.3、多分支语句结构

if [ 条件表达式 ]

then
        指令一
elif [ 条件表达式 ]

then
        指令二
else
        指令三
fi 

--------------------------------if单分支脚本--------------------------------
[root@192 shell]# cat oneif.sh
#! /bin/bash
num1=$1
num2=$2

if [ "$num1" -eq "$num2" ]; then
        echo "$1等于$2"
        exit 0
fi

if [ "$num1" -gt "$num2" ]; then
        echo "$1大于$2"
        exit 2
fi

if [ "$num1" -lt "$num2" ]; then
        echo "$1小于$2"
        exit 1
fi
[root@192 shell]# sh oneif.sh 1 10
1小于10
[root@192 shell]# sh oneif.sh 5 5
5等于5
[root@192 shell]# sh oneif.sh 10 9
10大于9
[root@192 shell]# 

--------------------------------if双分支脚本--------------------------------
[root@192 shell]# cat towif.sh 
#! /bin/bash

num=$1
if [ "$num" == "男" ];then
        echo "boy"
else
        echo ”gril“
fi
[root@192 shell]# sh towif.sh 男
boy
[root@192 shell]# sh towif.sh 女
”gril“
[root@192 shell]# 

--------------------------------if多分支脚本--------------------------------
[root@192 shell]# cat three.sh 
#! /bin/bach

age=$1

if [ "$age" -eq "18" ];then
        echo "刚好成年"
elif [ "$age" -lt "18" ];then
        echo "未成年"
elif [ "$age" -gt "18" ];then
        echo "青少年"
else 
        echo "中年、老年"
fi
[root@192 shell]# bash three.sh 20
青少年
[root@192 shell]# bash three.sh 23131
青少年
[root@192 shell]# bash three.sh s
three.sh: 第 5 行:[: s: 期待整数表达式
three.sh: 第 7 行:[: s: 期待整数表达式
three.sh: 第 9 行:[: s: 期待整数表达式
中年、老年
[root@192 shell]# 

2.2、for循环

格式:

        for 变量名 in 取值列表        
        do 
                命令序列(命令行)
        done

写成一行:

        for 变量名 in 取值列表; do 命令序列(命令行); 命令序列(命令行) done;

[root@192 shell]# cat for.sh     #for循环脚本
#! /bin/bash

for str in This is a string      #空格隔开,每个字符为单独的
do
    echo $str
done

[root@192 shell]# sh for.sh 
This
is
a
string
[root@192 shell]# 
[root@192 shell]# 
[root@192 shell]# 
[root@192 shell]# cat for.sh 
#! /bin/bash

for num in {1..10}
do
        echo $num
done

[root@192 shell]# sh for.sh 
1
2
3
4
5
6
7
8
9
10
[root@192 shell]# 

2.3、while循环

while 循环用于不断执行一系列命令,也用于从输入文件中读取数据。

格式:

        while 条件表达式
        do
                    命令序列(命令行)
        done

[root@192 shell]# cat while.sh 
#! /bin/bach

num=1
while (($num<=10)) 
do
        echo $num
        let "num++"
done
[root@192 shell]# sh while.sh 
1
2
3
4
5
6
7
8
9
10
[root@192 shell]# 

2.4、until循环

until 循环执行一系列命令直至条件为 true 时停止。

until 循环与 while 循环在处理方式上刚好相反。

一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。

格式:

        until 条件表达式
        do
                命令序列(命令行)
        done

[root@192 shell]# cat until.sh 
#!/bin/bash

i=1
until [ $i -gt 5 ]
do
        echo $i
        let i++
done
[root@192 shell]# sh until.sh 
1
2
3
4
5
[root@192 shell]# 

2.5、case判断

格式:

        case 变量 in
        模式1)
                命令序列1
        ;;
        模式2)
                命令序列2
        ;;
        模式3)
                命令序列3
        ;;
 *)
        无匹配后命令序列
esac

[root@192 shell]# cat case.sh
#! /bin/bash

echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read num                #从控制台接受参数

case $num in
        1)
                echo '你选择了 1'
                ;;
        2)
                echo '你选择了 2'
                ;;
        3)
                echo '你选择了 3'
                ;;
        4)
                echo '你选择了 4'
                ;;
        *)
                echo '你没有输入 1 到 4 之间的数字'
                ;;
esac
[root@192 shell]# sh case.sh 
输入 1 到 4 之间的数字:
你输入的数字为:
1
你选择了 1
[root@192 shell]# 

2.6、跳出循环 

2.6.1、break 命令

break 命令允许跳出所有循环(终止执行后面的所有循环)。

2.6.2、continue 命令

continue 命令与 break 命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。

六、函数 

linux shell 可以用户定义函数,然后在shell脚本中可以随便调用。

shell中函数的定义格式如下:

        函数名称(){

                函数体(命令序列)

        }

[root@192 shell]# cat fun.sh 
#!/bin/bash

funsum(){
        echo "请输入第一个数字:"
        read num1
        echo "请输入第二个数字:"
        read num2
        echo "请输入运算符号:"
        read num3
        echo “$num1 $num3 $num2 的结果为:$(($num1$num3$num2))”
}

funsum            #调用funsum函数
[root@192 shell]# sh fun.sh 
请输入第一个数字:
1
请输入第二个数字:
2
请输入运算符号:
+  
“1 + 2 的结果为:3”
[root@192 shell]# 

[root@192 shell]# cat fun.sh 
#!/bin/bash

funsum(){
        echo "请输入第一个数字:"
        read num1
        echo "请输入第二个数字:"
        read num2
        echo "请输入运算符号:"
        read num3
        echo “$num1 $num3 $num2 的结果为:”
        return $(($num1$num3$num2))        #return结果
}

funsum
echo "您输入两个数字的结果为:$?"
[root@192 shell]# sh fun.sh 
请输入第一个数字:
4
请输入第二个数字:
6
请输入运算符号:
+
“4 + 6 的结果为:”
您输入两个数字的结果为:10
[root@192 shell]# 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值