1

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?

5

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
6
  • 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 unix.stackexchange.com/a/277145/674, and unix.stackexchange.com/a/43389/674
    – Tim
    Apr 18 '16 at 17:15
  • 1
    @Tim The official definition is this one. See also here. "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
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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