Variable doesn't expand while passing as a par

2019-09-05 02:29发布

问题:

I was trying to run some docker-compose command over ssh using bash script like below. I mean I have an executable shell script deploy.sh which contains below code snippets

ssh -tt -o StrictHostKeyChecking=no root@142.32.45.2 << EOF
DIR=test
echo \${DIR}
docker-compose --project-name \${DIR} up -d
EOF

But the DIR variable doesn't get expanded while passing as a parameter to docker-compose. It executes like below. While echo \${DIR} gives correct output i.e test.

docker-compose --project-name ${DIR} up -d

回答1:

ssh -tt -o StrictHostKeyChecking=no root@142.32.45.2 <<'EOF'
DIR=test
echo ${DIR}
docker-compose --project-name ${DIR} up -d
EOF

Get rid of the \$ - it is preventing your variable expansion. But on second review, I see that's your intention. If you want to prevent all variable expansion until your code gets executed on the remote host, try putting the heredoc word in quotes. That way, the $ gets passed to the script being passed to ssh.

As a second suggestion ( as per my comment below ), I would consider just sending a parameterized script to the remote host and then executing it ( after changing its permissions ).

# Make script
cat >compose.sh <<'EOF'
#!/bin/bash
DIR=$1
docker-compose --project-name $DIR
EOF

scp -o StrictHostKeyChecking=no compose.sh root@142.32.45.2: 
ssh -o StrictHostKeyChecking=no root@142.32.45.2 chmod +x ./compose.sh \; ./compose.sh test