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 :
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 ?
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.)
The tail
is running in the bash script on your local machine, not on the remote host. The substitution is getting made before you even execute the ssh
command.
Your script can be replaced with simply:
ssh -T user@$123.456.789.123 tail www/index.htm
If you want to send those commands to the remote server, you can write
ssh -T user@$123.456.789.123 'cd www && var=$(tail index.htm) && echo $var'
Note that conditioning the next command on the result of the previous allows SSH to return a meaningful return code. In your heredoc, whatever happens (eg tail
fails), SSH will return with $?=0 because echo
will not fail.
Another option is to create a script there and launch it with ssh.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.