2

From https://unix.stackexchange.com/a/276611/674

When bash is run with -c, it is considered a non-interactive shell, and it does not read ~/.bashrc, unless is -i specified. So,

$ type cp
cp is aliased to ‘cp -i’          # Defined in  ~/.bashrc

$ cp .file1 file2
cp: overwrite ‘file2’? n

$ bash -c "cp .file1 file2"
                                  # Existing file is overwritten without confirmation!
$ bash -c -i "cp .file1 file2"
cp: overwrite ‘file2’? n

Is the shell created by bash -i -c <command> interactive or non-interactive?

Such a shell doesn't accept a command from stdin, does it? So it is not interactive, is it?

Such a shell reads ~/.bashrc, so it can't be non-interactive, can it?

Tim
  • 98,580
  • 191
  • 570
  • 977

1 Answers1

6

Use $-

From the Bash Reference Manual:

To determine within a startup script whether or not Bash is running interactively, test the value of the ‘-’ special parameter. It contains i when the shell is interactive.

For this example,

$ bash -c 'echo $-'      # This is a non-interactive shell
hBc

$ bash -i -c 'echo $-'   # This is an interactive shell
himBHc
Michael Durrant
  • 41,213
  • 69
  • 165
  • 232
Guido
  • 4,014
  • 13
  • 22
  • Thanks. For `bash -i -c`, if it is an interactive shell, can it accept a command from stdin? – Tim Apr 18 '16 at 16:51
  • 1
    @Tim It can accept a command from stdin even if it is a non-interactive shell, because both types of shell started with `bash -c` **are still attached to the current terminal**. Consider this simple "command interpreter", which will execute the command `ls` from stdin despite running as a non-interactive shell: `echo ls | bash -c 'read p; eval "$p"'` – Guido Apr 18 '16 at 17:08
  • How do you define if a shell is interactive or non-interactive? I thought that accepting a command from stdin is the defining characteristic. See http://unix.stackexchange.com/a/277145/674, and http://unix.stackexchange.com/a/43389/674 – Tim Apr 18 '16 at 17:15
  • 1
    @Tim The official definition is [this one](http://www.gnu.org/software/bash/manual/html_node/What-is-an-Interactive-Shell_003f.html#What-is-an-Interactive-Shell_003f). See also [here](http://www.gnu.org/software/bash/manual/html_node/Interactive-Shell-Behavior.html#Interactive-Shell-Behavior). "Interactive" vs. "non-interactive" primarily refers to the shell's behavior, not where it gets its input from. – Guido Apr 18 '16 at 17:26
  • I really think that one isn't a definition in terms of what interactive means, but enumeration of all the ways to invoke an interactive shell. – Tim Apr 18 '16 at 17:29
  • 1
    The example `echo ls | bash -c 'read p; eval "$p"'` accepts input to command `read` from stdin, and it doesn't accept a command from stdin. – Tim Apr 18 '16 at 18:04