Nested herodoc order of operations

Viewed 38

I have the following code -

ssh host sh -s << EOF
cd /backup/

ls

psql -U user -d db << SQL
$(sed 's/${previous_quarter}/${current_quarter}/' table_quarters.sql);
$(sed 's/${previous_quarter}/${current_quarter}/' plans.sql);
SQL

EOF

This is the order of execution it is following when I execute it -

  1. table_quarters script
  2. plans script
  3. ls command.

Why is it not following this order of execution -

  1. ls command
  2. table_quarters script
  3. plans script
1 Answers

You are sending a string to the standard input of ssh. This string can only be constructed if the stuff in $(...) is run first, because these parts will be replaced by the output of the enclosed commands.

Once the string is expanded, it's send by ssh to the remote machine which runs the resulting commands in order.

If you want to run the expansions on the remote end, you need to properly escape the dollar signs.

Related