一、交互模式、非交互模式
- 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存在)。