bash初认识2环境变量和自定义变量

一环境变量和自定义变量

环境变量是可以被全部进程使用的变量,类似与全局变量

自定义变量只能被当前进程所使用,类似与局部变量

自定义变量转换成环境变量:export 变量名字

1.将自定义变量转换成环境变量

[root@westos ~]# name=sd
[root@westos ~]# bash  ##开启一个新的子进程
[root@westos ~]# echo $name

[root@westos ~]# exit   ##在子进程里面没有输出name的值,退出子进程
exit
[root@westos ~]# export name
[root@westos ~]# name=sd
[root@westos ~]# bash
[root@westos ~]# echo $name
sd
[root@westos ~]# echo $name  ##由于name被设置为环境变量,所以子进程可以使用
sd
[root@westos ~]# exit
exit
[root@westos ~]#
局部变量转换成环境变量的过程:

1.当启动一个shell时候,操作系统会分配一段空间记忆块给shell使用,子shell可以继承父shell的这个记忆块

2.当在一个进程中使用export这个修饰变量时候,变量被自动加载在这个记忆块中,这个记忆块中的所有变量,都被子进程使用

二read的使用方法

read 变量名字:为这个变量名字赋值,通过键盘输入

[root@westos ~]# read name
bacjk

reat -t 变量名字  :会等待t秒,在ts内为变量赋值,否则取消这个命令

[root@westos ~]# read -t 30 name
naalkca
[root@westos ~]# echo $name
naalkca
read -p 一段字符串提示  变量名字

[westos@westos ~]$ read -p "input your name:" name
input your name:rise
[westos@westos ~]$ echo $name
rise

declare的使用方法:

declare 选项  变量名称

选项选项含义
-i将变量设置为数字类型
-r将变量设置为只读类型
-a将变量设置为数组类型
-x将变量设设置为环境变量

[root@westos ~]# sum=100+200+300
[root@westos ~]# declare sum
[root@westos ~]# sum=100+200+300
[root@westos ~]# echo $sum  ##输出sum
100+200+300
[root@westos ~]# declare -i sum=100+200+300 ##定义成数字类型
[root@westos ~]# echo $sum
600


默认类型为字符串,所以100+200+300被当成字符串处理 
将自定义变量设置为环境变量

declare -x sum

将环境变量设置为自定义变量

declare +x sum

[root@westos ~]# declare -x sum
[root@westos ~]# export | grep sum
declare -irx sum="600"

declare -r sum:设置为只读

[root@westos ~]# declare -r sum
[root@westos ~]# sum=o
-bash: sum: readonly variable

declare -p sum:类变量的类型

[root@westos ~]# declare -p sum
declare -irx sum="600"
//将sum设置为自定义变量
 [root@westos ~]# declare +x sum
[root@westos ~]# declare -p sum
declare -ir sum="600"





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值