1

I need to run a small shell script using C popen call (which calls sh -c '<command>'). I can't get my script to work. I isolated the issue to this snippet:

#!/bin/bash

sh -c 'bash -xev -s << EOF a=1 echo "a=$a" EOF'

which outputs

a=1
+ a=1
echo "a="
+ echo a=
a=

What am I missing? Why can't I use variables from stdin?

(versions: GNU bash 5.1.4, dash 0.5.11+git20200708+dd9ef66-5)

ofo
  • 121

1 Answers1

4

The body of the here-document will be subject to parameter expansion, command substitution, and arithmetic expansion unless you quote or escape some part of the EOF:

$ sh -c 'bash -xev -s << \EOF
a=1
echo "a=$a"
EOF'
a=1
+ a=1
echo "a=$a"
+ echo a=1
a=1

You can also use regular quotes "EOF" or 'EOF'.

For more complex cases, for example where you want some but not all variables to be expanded by the outer shell, you can leave the EOF unquoted and escape specific variables like \$a - see for example

steeldriver
  • 81,074