Bash syntax in /etc/profile

317 views Asked by At

I just noticed this line in my /etc/profile, and I wondered what this if means and when it is true.

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

i iterates over several *.sh files.

Sorry if this is a silly question, but as you can imagine, looking for mostly symbols in Google is really not an option.

Thanks!

1

There are 1 answers

0
Etan Reisner On BEST ANSWER

From the OPTIONS section of the manpage:

-i        If the -i option is present, the shell is interactive.

From the Special Parameters section of the manpage:

  -      Expands  to  the  current option flags as specified upon invoca-
         tion, by the set builtin command, or  those  set  by  the  shell
         itself (such as the -i option).

From the Parameter Expansion section of the manpage:

  ${parameter#word}
  ${parameter##word}

The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘‘#’’ case) or the longest matching pattern (the ‘‘##’’ case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

So "${-#*i}" says expand the $- variable and remove from the start of the string until the letter i. That expansion is then compared != against the expansion of $- (the same variable only unmodified).

When those are not the same it means the first expansion removed some contents which means the letter i appeared in the value of $- which means that (since -i is not an argument to set) that the -i argument was passed to the shell and the shell is an interactive shell.