2

This question already has an answer here:

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.

marked as duplicate by Xiong Chiamiov, Stephen Rauch, xhienne, Community Aug 2 '17 at 17:22

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • the $- contains the current shell options. – Andy Aug 1 '17 at 23:16
  • Dang, missed that dupe, sorry. – Xiong Chiamiov Aug 2 '17 at 15:02
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.

  • 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 at 2:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.