linux中export的用法

使用HISTTIMEFORMAT="%F###%T"(历史记录格式)来演示

查看:

set可以查看自定义变量,环境变量,函数

env可以查看环境变量

还有printenv,declare -x ,export 列出当前shell已存在的环境变量,不是全部,且自定义变量不会列在其中

[root@hecs-98663 ~]# SEX="male"
[root@hecs-98663 ~]# echo $SEX
male
[root@hecs-98663 ~]# bash
[root@hecs-98663 ~]# echo $SEX

[root@hecs-98663 ~]# exit
exit
[root@hecs-98663 ~]# env | grep male
//没有
[root@hecs-98663 ~]# tail -n 1 .bashrc 
HISTTIMEFORMAT="%F###%T"
[root@hecs-98663 ~]# bash
[root@hecs-98663 ~]# echo $HISTTIMEFORMAT
%F###%T
[root@hecs-98663 ~]# exit
exit

如何把自定义的变量延申进子shell

[root@hecs-98663 ~]# export SEX
[root@hecs-98663 ~]# bash
[root@hecs-98663 ~]# echo $SEX
male
[root@hecs-98663 ~]# exit
exit
[root@hecs-98663 ~]# export NAME="bell"
[root@hecs-98663 ~]# echo $NAME
bell
[root@hecs-98663 ~]# bash
[root@hecs-98663 ~]# echo $NAME
bell

退出终端就会失效

[root@hecs-98663 ~]# logout
[root@hecs-98663 ~]# echo $SEX

[root@hecs-98663 ~]# echo $NAME

[root@hecs-98663 ~]# 

如果要永久有效

当前用户有效:~/.bashrc

所有用户有效:/etc/profile

如果export 。。。本shell与子shell有效

如果没有export 只有本shell有效

如何删除环境变量

[root@hecs-98663 ~]# env | grep HISTTIMEFORMAT
HISTTIMEFORMAT=%F###%T
[root@hecs-98663 ~]# unset HISTTIMEFORMAT
[root@hecs-98663 ~]# env | grep HISTTIMEFORMAT
[root@hecs-98663 ~]# tail -n 1 .bashrc
HISTTIMEFORMAT="%F###%T"
[root@hecs-98663 ~]# source .bashrc 
[root@hecs-98663 ~]# tail -n 1 .bashrc
HISTTIMEFORMAT="%F###%T"
[root@hecs-98663 ~]# env | grep HISTTIMEFORMAT
[root@hecs-98663 ~]# 


退出终端重新登陆
[root@hecs-98663 ~]# tail -n 1 .bashrc
HISTTIMEFORMAT="%F###%T"
[root@hecs-98663 ~]# env | grep HISTTIMEFORMAT
HISTTIMEFORMAT=%F###%T
[root@hecs-98663 ~]# tail -n 1 .bashrc
HISTTIMEFORMAT="%F###%T"
[root@hecs-98663 ~]# env | grep HISTTIMEFORMAT
HISTTIMEFORMAT=%F###%T
[root@hecs-98663 ~]# vim .bashrc
[root@hecs-98663 ~]# tail -n 1 .bashrc 
NAME="zs"
[root@hecs-98663 ~]# source .bashrc 
[root@hecs-98663 ~]# env | grep NAME
HOSTNAME=hecs-98663
LOGNAME=root
[root@hecs-98663 ~]# echo $NAME
zs
[root@hecs-98663 ~]# bash
[root@hecs-98663 ~]# echo $NAME
zs

因为一个变量创建时,它不会自动的被在它之后创建的shell进程所知;这时,可用export命令向后面的shell传递变量的值。

export命令用于将shell变量输出为环境变量,或者将shell函数输出为环境变量。

参数说明:

  • -f:代表[变量名称]中为函数名称。
  • -n:删除指定的变量;实际未删除,只是不会输出到后续指令的执行环境中。
  • -p:显示所有的shell赋予子程序的环境变量。

实例1:显示当前所有的环境变量

$ export -p

实例2:设置环境变量

$ export PATH=$PATH:/home/dabai/test/bin
posted @ 2023-07-15 22:30  Bre-eZe  阅读(109)  评论(0)    收藏  举报