Score:3

Question about bash behavior with non-interactive mode

pl flag

I basically need to understand the following behavior:

$ echo $SHELL
/bin/bash
$ bash -c echo $SHELL

bash -c echo $SHELL produces a blank output, and this confuses me because I would expect the SHELL to be set. This is true for $BASH_VERSION as well.

Can someone explain this to me?

Thanks for your time!

Score:7
hr flag

From man bash:

   -c        If the -c option is present, then commands are read from  the
             first non-option argument command_string.  If there are argu‐
             ments after the command_string, the  first  argument  is  as‐
             signed  to $0 and any remaining arguments are assigned to the
             positional parameters.

In bash -c echo $SHELL, the "first non-option argument" is echo, while $SHELL is expanded by your current interactive shell and passed to bash as positional parameter $0. Since echo has no arguments itself, bash -c echo prints an empty string. Meanwhile, $0 is set to /bin/bash but ignored.

Depending on what you are trying to do, you can either do

bash -c 'echo $SHELL'

which passes echo $SHELL as command_string to the non-interactive bash shell (outputing the value of the non-interactive shell's $SHELL), or

bash -c 'echo $0' $SHELL

which passes (the expansion of) the interactive shell's $SHELL to the non-interactive bash shell as $0, then echoes its value.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.