What does "[[ $- != *i* ]] && return" mean?

I have this line in my .bashrc and I would like to know what exactly this means

# If not running interactively, don't do anything
[[ $- != *i* ]] && return

Solution 1:

  • $- means 'current flags'.
  • echo $- returns "himBH". Those are all defaults.
  • so ... [[ $- != *i* ]] && return actually does what it says above in a comment: it checks if the interactive flag is set. The [[ and ]] make it a boolean so it ends up in a "true" or "false". "false && return" makes it go on "true && return" makes it execute the return.

The default flags explained in more detail:

h is for "hash all": this tells bash to remember the locations of commands it has found through querying your PATH.

i is for "interactive": entering input & getting back output.

m is for "monitor": this enables job control

B is for "brace expand". This allows you to use brace expansion

H is for "history expand". This is what enables you to rerun a command from your history by prefacing its number with an exclamation point


By the way. I have ...

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

Basically does the same but easier to read I assume.

Solution 2:

Basically it means "If the shell flags don't contain a lowercase i, then stop the function/script here".

[[ ]]

denotes a conditional expression in bash

$-

means the shell flags. It will contain "i" if the shell is interactive (ie. you can type commands, as opposed to, it's executing a script)

!=

simply means "not equal to".

*i*

is a wildcard pattern that matches anything containing "i"

return

without any arguments just means stop the execution of the current function or script.

&&

is the logical AND operator. The expression at the right, in this case return, will only be evaluated (executed) if the expression at the left is true. So in many programming languages, a && b is a shorthand for if a then b -- this is called "short-circuit evaluation" and it drives programming teachers crazy when you use it :D

Solution 3:

I would assume it's like it says: if bash isn't open in an interactive shell, then don't do anything.

I don't know the whole function, but there are probably commands and flags set below that line in case you do have bash open in a TTY.