Linux /etc/profile 關鍵步驟解析

一、交互模式、非交互模式

  • himBH 是 interactive 模式
  • hB 是 non-interactive 模式
[root@lzq ~]# echo $-
himBH
[root@lzq ~]# echo "${-#*i}"
mBH				# ${-#*i} Remove Smallest Prefix Pattern. 移除了 hi 。
[root@lzq ~]# bash a.sh
hB
hello world!
[root@lzq ~]# cat a.sh
#!/bin/bash
echo $-
echo "hello world!"


二、/etc/profile 關鍵步驟

  • sh.local 文件的內容
  • 我們增加環境變量可以覆蓋此文件
cat sh.local
#Add any required envvar overrides to this file, it is sourced from /etc/profile
for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then # 文件是否可讀判斷
    	# # interactive 模式判斷
        if [ "${-#*i}" != "$-" ]; then # 截取後是否相等,判斷 i 是否存在
            . "$i"		# interactive 模式, 執行每個 *.sh
        else
            . "$i" >/dev/null # non-interactive 模式, 丟棄不執行。
        fi
    fi
done


# if [ "${-#*i}" != "$-" ]
# It's checking whether the shell is interactive

三、What does the if [ “${-#*i}” != “$-” ] mean?

$- is a variable which stores the current options set by the shell.

${-#*i} is using substring removal to remove the shortest match to the pattern *i from the beginning of the variable.
So if$- has the valueabcifOO then ${-#*i} would be fOO.

This means that the test

[ "${-#*i}" != "$-" ]

will be true if the variable $- contains the option i , which means interactive mode is switched on.

All together this means that the output will only be redirected to /dev/null if you are in interactive mode.

$- 意味着shell標誌。

${-#*i} 意味着shell標誌減去第一個匹配 *i 。

如果這兩個不相等,那麼該 shell 被認爲是交互式的(標誌i存在)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章