Search code examples
bashsshexecutiontail

Why is the order of execution inversed in this bash script?


I have this script :

ssh -T user@$123.456.789.123 <<EOF

    cd www

    var=$(tail index.htm)

    echo $var

EOF

What I thought it should do is :

  1. Connect to the server through SSH,
  2. then change to the folder www,
  3. then store the tail of index.htm into the variable var
  4. and finally echo the result.

Instead it seems that tail is executed before the change of folder, and thus doesn't find the index.htm file.

I've tried with different commands, and each time it seems the result from command substitution I'm trying to store into a variable is executed right after the SSH connexion is opened, before any other piece of script.

What am I missing here ?


Solution

  • The $(...) is being expanded locally, before the contents of the here document are passed to ssh. To send literal text to the remote server, quote the here document delimiter.

    ssh -T user@$123.456.789.123 <<'EOF'
        cd www
        var=$(tail index.htm)
        echo "$var"
    EOF
    

    (Also, quote the expansion of $var to protect any embedded spacing from the shell.)