Bash – the advantage of using bash -c over using a here string

bashhere-string

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

They seem to achieve the same effect.

Best Answer

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.

Related Question