将变量作为参数传递给heredoc块中的docker-compose命令时,变量不会扩展 [英] Variable doesn't expand while passing as a parameter to docker-compose command inside heredoc block
问题描述
我试图使用bash脚本在ssh上运行一些docker-compose命令,如下所示。我的意思是我有一个可执行的Shell脚本deploy.sh,其中包含以下代码段
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
但是DIR变量在作为参数传递给docker-compose时不会扩展。它执行如下。而 echo \ $ {DIR}
给出正确的输出,即 test 。
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
推荐答案
ssh -tt -o StrictHostKeyChecking=no root@142.32.45.2 <<'EOF'
DIR=test
echo ${DIR}
docker-compose --project-name ${DIR} up -d
EOF
摆脱\ $-它会阻止变量扩展。但是,在第二次审核中,我看到的是您的意图。如果要防止所有变量扩展,直到代码在远程主机上执行,请尝试将Heredoc词放在引号中。这样,$将传递到传递给ssh的脚本。
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
这篇关于将变量作为参数传递给heredoc块中的docker-compose命令时,变量不会扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!