Shell基本了解

一、什么是shell?

Shell是linux的一外壳,它包在linux内核的外面,为用户和内核之间的交互提供了一个接口,当用户下达指令给操作系统的时候,实际上是把指令告诉shell,经过shell解释,处理后让内核做出相应的动作,系统的回应和输出的信息也由shell处理,然后显示在用户的屏幕上
二、什么是shell脚本?
简单的说,当命令或者程序不在命令行执行,而是通过一个程序文件来执行,这个程序就被称为shell脚本,也就是在shell脚本里内置了多条命令,语句,循环控制,然后将这些命令一次性执行完毕,这种通过文件执行命令的方式称为非交互式

二、脚本开发规范

一个完整的shell脚本需要有以下几个部分:
脚本名:最好以.sh结尾
第一行:#!/bin/bash
指定解释器:由哪个程序来执行脚本内容
#!:幻数
注意:#!/bin/bash必须写在第一行,否则会被认为是注释
有用户判断,否则任何用户都可以执行这个脚本
有流程控制,否则只是把简单的命令进行顺序操作,没有成功与否的判断
注释:可以命令后,也可以自成一行(方便自己也方便他人)

三、 脚本执行方法

1.sh script.sh | bash script.sh    
没有执行权限时
[root@localhost ~]# sh log.sh
Logs cleaned up…

2.path/script.sh | ./script(要在脚本的当前目录下)   
绝对路径,需要给脚本添加执行权限
[root@localhost ~]# /root/log.sh
bash: /root/log.sh: Permission denied ##没有执行权限时,不可执行
[root@localhost ~]# chmod +x log.sh
[root@localhost ~]# /root/log.sh ##添加权限后正常执行
Logs cleaned up…

3.source script.sh | . script.sh
这种方式会使用source或.号来读如入指定shell文件,并会把其他shell中的变量值或函数返回给父shell继续使用
前两种方式,在执行脚本的时候,会默认打开一个新的shell,而新shell的变量值和函数不会返回给父shell
[root@localhost mnt]# vim test.sh
#!/bin/bash
username=zafkiel
[root@localhost mnt]# sh test.sh
[root@localhost mnt]# echo $username ##无返回值

[root@localhost mnt]# source test.sh
[root@localhost mnt]# echo $username ##有返回值

四。变量的数值计算

  1. expr命令
    [root@server mnt]# a=123
    [root@server mnt]# expr $a + 10
    133
    [root@server mnt]# expr $a - 10
    113
    [root@server mnt]# expr $a * 10 (此命令不能识别*,必须加)
    expr: syntax error
    [root@server mnt]# expr $a * 10
    1230
    [root@server mnt]# expr $a / 10
    12
    [root@server mnt]# expr $a % 10
    3

2. [ ] []和 (())表达式

[root@server mnt]# echo $[a+10]
20
[root@server mnt]# echo $[a-10]
0
[root@server mnt]# echo $[a*10]
100
[root@server mnt]# echo $[a/10]
1
[root@server mnt]# echo $[a%10]
0
[root@server mnt]# echo $((a+10))
20
[root@server mnt]# echo $((a-10))
0

3。 let命令

let命令在执行后会保存新的值
[root@server mnt]# let a+=10
[root@server mnt]# echo $a
20
[root@server mnt]# let a-=10
[root@server mnt]# echo $a
10
[root@server mnt]# let a*=10
[root@server mnt]# echo $a
100
[root@server mnt]# let a/=10
[root@server mnt]# echo $a
10
[root@server mnt]# let a%=10
[root@server mnt]# echo $a
0

猜你喜欢

转载自blog.csdn.net/gordzafkiel/article/details/87226540
今日推荐