Bash Check if Shell on Interactive or Login

In Bash, you can check whether the shell is running in an interactive or login mode using the provided commands. Here’s an explanation of each command and what it checks for:

  1. [[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive':

    • This command checks the value of the special shell variable $-, which contains a string of options and flags that are currently set for the shell.
    • The *i* pattern is used to check if the letter ‘i’ appears anywhere in the value of $-. If it does, it indicates that the shell is running in interactive mode.
    • If ‘i’ is found, it echoes ‘Interactive’, otherwise, it echoes ‘Not interactive’.
  2. shopt -q login_shell && echo 'Login shell' || echo 'Not login shell':

    • This command uses the shopt built-in command to check the status of a shell option called login_shell.
    • If shopt -q login_shell returns true (exit status 0), it means that the shell is a login shell, so it echoes ‘Login shell’.
    • If shopt -q login_shell returns false (exit status non-zero), it means that the shell is not a login shell, so it echoes ‘Not login shell’.

You can use these commands in your Bash scripts or in the terminal to determine whether the shell is running interactively or as a login shell.

Here’s the code in markdown format:

1
2
3
4
5
6
```bash
# Check if the shell is running in interactive or non-interactive mode
[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'

# Check if the shell is a login shell or not
shopt -q login_shell && echo 'Login shell' || echo 'Not login shell'

You can run this code in a Bash terminal to see the output based on the current shell's mode.
0%