0

I'm trying to generate a file within a bash script using EOF. The file is being generated correctly but, a piece of javascript code where I define a variable is being left out and malforming the code:

Javascript/Bash Code Snippet

cat << EOF > map.php
$( "#slider" ).slider({
  value:60,
min: 1.0,
max: 100.0,
  animate: true,
animate: 500,
slide: function( event, ui ) {
   historicalOverlay.setOpacity( ui.value/100 );
     }
});
EOF

Result

.slider({
  value:60,
min: 1.0,
max: 100.0,
  animate: true,
animate: 500,
slide: function( event, ui ) {
   historicalOverlay.setOpacity( ui.value/100 );
     }
});
axiac
  • 68,258
  • 9
  • 99
  • 134
arnpry
  • 1,103
  • 1
  • 10
  • 26
  • See [this Q&A](https://stackoverflow.com/questions/4937792/using-variables-inside-a-bash-heredoc) about quoting in here-docs. – Benjamin W. Feb 25 '19 at 14:36

2 Answers2

2

All lines of a here-document are subjected to parameter expansion, command substitution, and arithmetic expansion.

The sequence $( "#slider" ) is a command substitution. The shell runs #slider (which is a no-op because it represents a comment) and replaces the sequence with the output of the command (no output).

If you want your script to output the fragment of JS verbatim you can put the delimiter of the here-document into single quotes:

cat << 'EOF' > map.php
$("#slider").slider({
  value:60,
  min: 1.0,
  max: 100.0,
  animate: true,
  animate: 500,
  slide: function( event, ui ) {
    historicalOverlay.setOpacity( ui.value/100 );
  }
});
EOF

This tells the shell to not expand any special sequence inside the text.

If the JS code contains pieces that need to be substituted (parameters, commands etc) you can let the delimiter unquoted and take care to escape any character that marks an expansion or substitution.

Applied to the code above, this leads to:

cat << EOF > map.php
\$("#slider").slider({
  value:60,
  min: 1.0,
  max: 100.0,
  animate: true,
  animate: 500,
  slide: function( event, ui ) {
    historicalOverlay.setOpacity( ui.value/100 );
  }
});
EOF
axiac
  • 68,258
  • 9
  • 99
  • 134
  • What if I have actual bash variables that I need to remain? i.e. a `date` command like `${YYYYMMDD}` – arnpry Feb 25 '19 at 13:47
  • Ok I fixed the issue... I added a \ in front of the line and it is not being read now. – arnpry Feb 25 '19 at 13:52
  • 1
    Alternatively: Put the parts that look like shell expansions into their own variables, e.g. `slider='$("#slider)'` (note: single quoted), which you can then interpolate into the here-document: `cat << EOF ... ${slider}.slider({ ...`. – melpomene Feb 25 '19 at 14:18
1

I added a backslash in front of the line/JS variable:

cat << EOF > map.php
\$( "#slider" ).slider({
  value:60,
min: 1.0,
max: 100.0,
  animate: true,
animate: 500,
slide: function( event, ui ) {
   historicalOverlay.setOpacity( ui.value/100 );
 }
});
EOF
arnpry
  • 1,103
  • 1
  • 10
  • 26