Sunday, October 9, 2022

[SOLVED] What does `bash -` do?

Issue

I recently saw the following line:

curl -fsSL https://deb.nodesource.com/setup_17.x | bash - 

What is the difference between bash and bash -? I tried running both variants, and they seem to do the same thing.

man bash didn't supply an answer either.


Solution

The commands are identical.

The author probably believes that passing - as an argument will make bash read commands from stdin but bash will do that anyway.

In fact, the bash man-page explains that - is equivalent to -- and terminates option processing:

--    A  --  signals the end of options and disables further option
      processing.  Any arguments after the -- are treated as  file‐
      names and arguments.  An argument of - is equivalent to --.

Note that if there was something after the -, then behaviour might be different. For example:

$ echo "echo foo" > ./-c
$ chmod +x ./-c
$ export PATH=.:"$PATH"
$ bash   -c "echo bar"
bar
$ bash - -c "echo bar"
foo
$

Note also, it is not the case that using bash - makes it a login shell. This can be demonstrated by adding something printable to ~/.bash_profile:

$ export HOME=$(mktemp -d)
$ cd
$ echo "echo login shell" > .bash_profile
$ echo "echo hello" | bash
hello
$ echo "echo hello" | bash -
hello
$ echo "echo hello" | bash -l
login shell
hello
$

The meaning in the manpage of "A login shell is one whose first character of argument zero is a -" is that the command name starts with a hyphen:

$ cat .bash_profile
echo login shell
$ ln -s /bin/bash ./notLoginShell
$ ln -s /bin/bash ./-isLoginShell
$ export PATH=~:"$PATH"
$ echo "echo hello" | notLoginShell
hello
$ echo "echo hello" | -isLoginShell
login shell
hello
$


Answered By - jhnc
Answer Checked By - David Goodson (WPSolving Volunteer)