我們都知道CentOS系統中有四個定義環境變量的配置文件,分別是/etc/profile和/etc/bashrc以及家目錄下的~/.bashrc和~/.bash_profile,那麼我們系統啓動時是以什麼順序來讀取這些環境變量配置文件的呢?
對於這個問題我們可以寫一個腳本來測試:
#!/bin/bash
##############################################################
# File Name: shift.sh
# Version: V1.0
# Author: li qian
# Organization:
# Created Time : 2017-10-28 15:21:08
# Description:
##############################################################
rm -f /tmp/shijian
until [ $# -eq 0 ]
do
sed -i '/^echo.*shijian/d' "$1"
sed -i "1i echo ${1}1 $\(date +%T%N\) >> /tmp/shijian" "$1"
sed -i "\$a echo ${1}2 $\(date +%T%N\) >> /tmp/shijian" "$1"
shift
done
reboot
[root@centos7_2 ~]# sh /server/scripts/shift.sh /etc/profile /etc/bashrc /root/.bashrc /root/.bash_profile
執行完腳本,系統會自動重啓,然後我們會在/tmp目錄下的shijian文件看到我們要的結果
[root@centos7_2 ~]# cat /tmp/shijian
/etc/profile1 15:42:52818124419
/etc/profile2 15:42:53809866251
/root/.bash_profile1 15:42:53887264247
/root/.bashrc1 15:42:53971852375
/etc/bashrc1 15:42:54069565295
/etc/bashrc2 15:42:54118786824
/root/.bashrc2 15:42:54185749478
/root/.bash_profile2 15:42:54237113170
結論:系統在啓動時加載環境變量配置文件的順序是/etc/profile-->~/.bash_profile-->~/.bashrc-->/etc/bashrc,同時我們也發現了在加載這些文件的同時還會調用其他文件,所以我們在定義全局環境變量和局部環境變量時最好分別在統一在一個文件(例如全局統一在/etc/profile局部統一在~/.bash_profile或~/.bashrc)中定義,否則會有覆蓋的風險!