shell编程
一、shell简介
shell语言是一个C语言编写的脚本语言,它是用户与linux的桥梁
shell编程:通常指的是学习shell命令语法后,利用这套语法开发脚本程序,操作、访问内核服务。而不是使用C语言去编写一个shell程序。
shell解释器:unix默认sh,Linux的默认的是Bash shell,bash兼容sh,针对sh编写的shell代码可以不加修改地在bash中运行。
二、shell变量
shell中有3中变量:用户变量、环境变量、特殊变量
用户变量在编程过程中使用最多
环境变量主要是在程序运行时需要设置
特殊变量在对参数判断和命令返回值判断是会使用
变量的定义语法:变量名=变量值
变量的定义需要遵循的规则
1.变量名可以有字母、数字、下划线组成,但是不能以数字开头,不能使用关键字,严格区分大小写
2.在Bush中,变量的默认类型都是字符串型,如果进行数值运算,则必须要使用特殊命令
3.变量用等号“=”连接值,“=”左右两侧不能有空格。
4.变量值中如果有空格,则需要用单引号或者双引号包含,如 test=“hello world!”
5.在变量中,可以使用转义符“\”。
1.用户变量
定义普通变量:变量名=变量值 注意:“=”左右两侧不能有空格!!!
定义只读变量:readonly 变量名=变量值 注意:只读变量生命周期在窗口关闭或脚本执行后结束
获取变量值:$变量名 或者 ${变量名} 建议使用${变量名}因为它标识变量的边界范围
删除普通变量:unset 变量名
修改普通变量值:已有变量名=新变量值
修改普通变量为只读变量:readonly 变量名
[root@cent1 test]# name = "张三"
bash: name: command not found...
[root@cent1 test]# name="张三"
[root@cent1 test]# echo name
name
[root@cent1 test]# echo $name
张三
[root@cent1 test]# echo $name
张三
[root@cent1 test]# echo $name666
[root@cent1 test]# echo ${name}666
张三666
[root@cent1 test]# unset name
[root@cent1 test]# echo ${name}666
666
[root@cent1 test]# echo ${name}
[root@cent1 test]# readonly age=18
[root@cent1 test]# echo $age
18
[root@cent1 test]# unset age
-bash: unset: age: cannot unset: readonly variable
[root@cent1 ~]# exit
logout
Last login: Sat Mar 18 09:03:37 2023 from 192.168.88.1
[root@cent1 ~]# echo $age
2.环境变量
环境变量:值操作系统(Windows、Linux、Mac)在运行的时候,记录的一些关键信息,用以辅助系统运行。
注意:环境变量的名字习惯上用大写字