壳基础——变量,判断,循环

# shell脚本中要加上解释器# !/bin/bash


#用脚本打印出hello world


回声“hello world”退出


参数:参数是一个存储实数值的实体,脚本中一般被引用


#利用变量回显hello world,下面例子会回显两个hello world。

# !/bin/bash

=癶ello world”

echo $

回声“hello world”退出


如果参数后面加着其它内容,需要用{}

# !/bin/bash


=癶ello world”

echo ${},我来了

退出回显结果:

壳基础——变量,判断,循环


#计算字符串长度,hello world连空格,总共11

壳基础——变量,判断,循环


#一个执行成功的脚本返回值为0,不成功为非0

(root@localhost脚本)#明确

(root@localhost脚本)# sh hello.sh 

hello world,我来了

11 (root@localhost脚本)# echo $ ?

0

#判断一个目录内是否有某个文件,有则回显文件存在,没有则返回1

(root@localhost脚本)#猫test.sh 

# !/bin/bash

cd/home

如果[- f文件];然后

回声”文件存在“其他

fi

(root@localhost脚本)# sh test.sh 

(root@localhost脚本)# echo $ ?

(root@localhost脚本)#,



测试- d xx,目录是否存在

测试- f xx,文件是否存在

测试- B xx,是否为块文件

测试- x xx,是否为可执行文件

A情商,判断是否相等

A - ne,判断不相等

A勒,小于等于

A lt,小于

A gt,大于


#如果条件判断语句

如果[];然后

……

fi


#如果语句嵌套

如果[];然后

.......

elif[];然后

.......

elif[];然后

.......

……

fi

#测试举例,判断测试文件是否存在,如果存在对其进行备份操作。如果不在回显信息

壳基础——变量,判断,循环

#例子:输入一个数值判断其在哪个区间。小于80年大于100年,位于80年到100年之间,用的是如果嵌套!

(root@localhost脚本)#猫if.sh 

# !/bin/bash


阅读- p”请输入美元num:“num


如果(num勒80美元);然后

回声“num小于80”

elif (num通用80美元),,(num勒100美元);然后

回声“80年和100年之间的num”

其他回声“num大于100”

fi

壳基础——变量,判断,循环




的var var1 var2美元美元var3 var4……$ var

做,,,……

,,,……

完成

#例子:打印1到10数字

[root@localhost家里]#猫for1.sh 

# !/bin/bash



的var {1 . . 10},

做呼应" $ var "

睡眠2

完成(root@localhost家里)# sh for1.sh  1

3

4 5 6

7 8 9

10 [root@localhost家里]#,


#打印方块内容为嵌套

[root@localhost家里]# sh for2.sh 

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

* * * * * * * * *

[root@localhost家里]#猫for2.sh

# !/bin/bash


为((i=1; i<10;我+ +))

为((j=1; j<10; j + +))

做呼应- n“*”,

完成回声”

完成

#而循环,主要也是用于循环,另外还有继续(跳出继续下面语句,回归顶部命令行),打破(停止,退出循环)


#虽然语句

而[条件判断]

做…

……完成


#例子:根据条件判断的,输出1 - 10

(root@localhost脚本)#猫while.sh 

# !/bin/bash


var=1


而[$ var le 10]

做echo $ var

壳基础——变量,判断,循环