Home > Mobile >  sh -c doesn't recognize heredoc syntax
sh -c doesn't recognize heredoc syntax

Time:05-26

I think the two commands below should be identical, but given the heredoc, the shell produces an error. Is it possible to pass a heredoc to the -c argument of sh?

heredoc example

/bin/sh -c <<EOF
echo 'hello'
EOF

# ERROR: /bin/sh: -c: option requires an argument

simple string example

/bin/sh -c "echo 'hello'"

# prints hello

CodePudding user response:

The commands are not equivalent.

/bin/sh -c <<EOF
echo 'hello'
EOF

is equivalent to

echo "echo 'hello'" | /bin/sh -c

or, with here-string:

/bin/sh -c <<< "echo 'hello'"

but sh -c requires an argument. It would work with

echo "echo 'hello'" | /bin/sh

CodePudding user response:

I tried to post this as a comment but formatting code doesn't work well in comments. Using the accepted answer by @Benjamin W. as a guide, I was able to get it to work with this snippet

( cat <<EOF
echo 'hello'
EOF
) | /bin/sh

The magic is in how cat handles inputs. From the man page:

If file is a single dash (`-') or absent, cat reads from the standard input.

So cat can redirect stdin to stdout and that can be piped to /bin/sh

  • Related