您的位置:首页 > 运维架构 > Shell

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

2017-01-07 22:33 369 查看

一环境变量和自定义变量

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

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

自定义变量转换成环境变量: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"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: