11

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

They seem to achieve the same effect.

6
  • 3
  • 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 4 '17 at 4: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 4 '17 at 5:51
  • Would it be appropriate to delete the post from one of the sites then?
    – yosefrow
    Jun 4 '17 at 8: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. Jun 4 '17 at 13:52
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.

3
  • 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 4 '17 at 3:43
  • Well, bash <<< 'echo $1' /dev/stdin foo works too, and prints foo. Though setting $0 is somewhat more limited.
    – ilkkachu
    Jun 4 '17 at 20:17
  • bash <<< 'echo "$1"' /dev/stdin foo doesn't always work.  I got bash <<< 'echo "$1"' -s foo to work. Jun 5 '17 at 0:59

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.