[ "${-#*i}" != "$-" ] 在 sh 中做什么?

Xio*_*iov 2 shell-script

我在/etc/profileCentOS 机器上发现了这段可爱的代码片段:

for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done
Run Code Online (Sandbox Code Playgroud)

我知道它.sh从加载到文件中/etc/profile.d,但我对最后一个 if 语句感到困惑,if [ "${-#*i}" != "$-" ]. 这个语法是做什么的?我什至不知道在哪里查找。

xhi*_*nne 7

基本上,[ "${-#*i}" != "$-" ]检查您的外壳是否是交互式的。

$-包含用于 shell 执行的标志(例如:himBHi意思是 shell 是交互式的)。${-#*i}产生$-第一个后面的部分imBH在我们的例子中)。如果没有iin$-那么${-#*i}yield $-

这正是测试的内容:如果两个字符串不同,则意味着存在iin $-,换句话说,shell 是交互式的。