11

Is there any real benefit to using bash -c 'some command' over using bash <<< 'some command'

They seem to achieve the same effect.

yosefrow
  • 389
  • 3
  • 12
  • 3
    https://stackoverflow.com/questions/44350291/what-is-the-advantage-of-using-bash-c-over-using-a-here-string - [Do not cross-post](https://meta.stackexchange.com/q/64068/194222) – phemmer Jun 04 '17 at 04:28
  • Hi @Patrick thanks for the notice. I really wasn't sure about where the best place to post was. Since, on the one hand this is a Linux question, but on the other hand bash is a kind of scripting language and the other site has more visitors. In a case like this, where would the more appropriate place be to post? – yosefrow Jun 04 '17 at 04:53
  • 4
    @yosefrow: Either site would have been fine IMHO; but crossposting is obnoxious (you're asking people on both sites to spend time on your question, without giving them the benefit of each others' answers). – ruakh Jun 04 '17 at 05:51
  • Would it be appropriate to delete the post from one of the sites then? – yosefrow Jun 04 '17 at 08:22
  • 2
    Another minor difference is that `bash -c '...'` will work in shells that do not have herestrings. You are assuming that bash will be called within a bash shell but this will not always be the case. – Joel Cornett Jun 04 '17 at 13:52
  • The other copy has now been closed. – Michael Homer Jun 04 '17 at 22:05

1 Answers1

21

bash -c 'some command' retains access to the standard input of the caller, so read or commands reading from standard input will work normally. bash <<< 'some command' replaces that input with the line being passed in, so bash -c cat and bash <<< cat do different things.

$ bash -c cat
abc
abc
^D
$ bash <<< cat
$

On the other hand, you could make use of that feature to provide your own standard input to be used through $'...', if you're very careful:

$ bash <<< $'read x y\nabc def ghi\necho $y'
def ghi
$

I wouldn't want to rely on that, but it could be convenient sometimes.


bash -c also allows arguments to be passed to the script, and $0 to be set:

bash -c 'some command' sh abc def

will set $1 to abc and $2 to def inside some command.

Michael Homer
  • 74,824
  • 17
  • 212
  • 233
  • 3
    Syntax errors will also produce slightly different wording. Mainly that the `bash -c` ones mention `-c`, AFAIK. Not entirely pointless, as that can help track them down. `bash <<< 'script'` errors look just like ones in the parent script; `bash -c 'script'` ones do not. You can even label them: `bash -c 'script' label`. – derobert Jun 04 '17 at 03:43
  • Well, `bash <<< 'echo $1' /dev/stdin foo` works too, and prints `foo`. Though setting `$0` is somewhat more limited. – ilkkachu Jun 04 '17 at 20:17
  • `bash <<< 'echo "$1"' /dev/stdin foo` doesn't always work.  I got `bash <<< 'echo "$1"' -s foo` to work. – G-Man Says 'Reinstate Monica' Jun 05 '17 at 00:59