Shell: 在shell中的变量

一.变量的基本概念

1.变量的定义

变量:在内存当中的一片地址,在程序运行的过程中,它的数值是允许改变的量

  • 变量是用一串固定的字符来表示不固定的数值的一种方法
  • 在shell中,变量是不能永久保存在系统中的,必须在文件中声明

2.变量的种类
在shell中变量分为环境级变量,用户级变量,系统级变量

  • 环境级变量只在当前的shell中生效,shell关闭变量丢失
  • 用户级变量写在用户的骨文件中,只针对当前用户生效
  • 系统级变量写在系统的配置文件/etc/profile或者/etc/profile.d中,对于所有用户都生效。

二.变量的定义

1.shell变量的定义
在这里插入图片描述

[root@localhost mnt]# vim test.sh
文件编辑内容为:
#!/bin/bash
echo  $a
[root@localhost mnt]# chmod +x test.sh 
[root@localhost mnt]# /mnt/test.sh   ##不能输出a是因为之前定义的shell和这个脚本的shell是不同的

在这里插入图片描述
变量的正确定义方法如下:
在这里插入图片描述
注:``通用,$不通用

2.shell脚本中变量的定义方法

(1)环境级:

export a=1

(2)用户级:

[root@localhost mnt]# vim ~/.bash_profile  #用户级别的配置文件
[root@localhost mnt]# source ~/.bash_profile   ##生成
[root@localhost mnt]# echo $a

在这里插入图片描述
在这里插入图片描述
发现切换用户后变量不存在。

(3)系统级

[root@localhost ~]# vim /etc/profile
编辑内容:添加
export =1
[root@localhost ~]# source  /etc/profile #生成

在这里插入图片描述
在这里插入图片描述
测试:
在这里插入图片描述
系统级别的另一种定义方法:

添加验证之前先把系统级别文件先添加的注释了或者删除

[root@localhost ~]# cd /etc/profile.d/
[root@localhost profile.d]# ls
[root@localhost profile.d]# vim westos.sh

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
3.字符的转义及变量声明

单引号强引用,双引号弱引用
双引号:除了` ! ? $ 其他的都可以引用

三.Linux系统中命令别名的设定

1.用户级别的命令别名的设定

[root@localhost mnt]# vim ~/.bashrc
文件编辑内容为:
alias xie='vim'
[root@localhost mnt]# source ~/.bashrc  #生成

在这里插入图片描述
在这里插入图片描述
验证如下:
在这里插入图片描述
2.系统级别的命令别名的设定

[root@localhost profile.d]# vim westos.sh 
文件编辑内容为:
alias  xie='vim'
[root@localhost profile.d]# source westos.sh  #生成

在这里插入图片描述
验证如下:
在这里插入图片描述
变量练习:

(1)写脚本建立用户,存在的话显示改用户已经存在,不存在的话建立该用户

[root@localhost mnt]# vim usr_create.sh 

脚本编辑内容为:
在这里插入图片描述
验证如下:
在这里插入图片描述
在这里插入图片描述
(2)建立用户的添加,删除和退出,c,d,e

[root@localhost mnt]# vim user_ctl.sh

脚本编辑内容为:
在这里插入图片描述
验证如下:
在这里插入图片描述如果输入错误的字符选择就会直接退出,但是一般有建立删除用户有错误的时候要回到起点重新选择,所以脚本改进如下:

[root@localhost mnt]# cat user_ctl.sh > test.sh
[root@localhost mnt]# vim test.sh

脚本修改内容如下:
在这里插入图片描述
验证如下:
在这里插入图片描述
可以看到当有输入错误的字符选择时会直接循环再此输入1,而不会直接退出,并且当建立的用户存在时也不会直接退出,而是提醒再次建立新用户。

猜你喜欢

转载自blog.csdn.net/weixin_44224288/article/details/88319740