2

I found this lovely snippet of code in /etc/profile on a CentOS box:

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

I know that it loads in the .sh files from /etc/profile.d, but I'm confounded by the last if statement, if [ "${-#*i}" != "$-" ]. What is this syntax doing? I'm not even sure where to look it up.

2
  • the $- contains the current shell options.
    – Andy
    Aug 1, 2017 at 23:16
  • Dang, missed that dupe, sorry. Aug 2, 2017 at 15:02

1 Answer 1

7

Basically, [ "${-#*i}" != "$-" ] checks whether your shell is interactive.

$- contains the flags used for your shell execution (for example: himBH, the i meaning that the shell is interactive). ${-#*i} yields the part of $- that follows the first i (mBH with our example). If there is no i in $- then ${-#*i} yields $-.

That's exactly what the test is about: if the two strings are different, that means that there is a i in $-, in other words that the shell is interactive.

1
  • It's made more confusing because i is also the loop variable name. I spent some time trying to see how it worked according to the bash docs, to no avail. Thanks for the explanation.
    – Edmund
    Mar 13, 2019 at 2:23

Not the answer you're looking for? Browse other questions tagged .