使用" here document"在for循环中

时间:2017-07-21 11:13:28

标签: linux bash shell ssh nohup

我需要在here文档中包含一些代码并使用ssh:

运行它
for service in ${services[@]}
do
ssh -tt root@${server} service=${service} 'bash -s' << 'ENDSSH'
    ps axf | grep "service-${service}" | grep -v grep | awk '{print "kill -9 " $1}' | sh
    nohup java -jar service-${service}.jar >> nohup.out 2>&1 &
ENDSSH
done

然而,for循环可以只进行第一次运行,ssh似乎捕获了stdin,for循环永远挂在那里。我该如何让ssh立即返回并继续下一步执行?

1 个答案:

答案 0 :(得分:3)

首先,您可以替换它:

ps axf | grep "service-${service}" | grep -v grep | awk '{print "kill -9 " $1}' | sh

有了这个:

pkill -f "service-${service}"

您可以跳过&#34; here here&#34;并简化:

for service in ${services[@]}
do
{
    echo "pkill -f service-${service}";
    echo "nohup java -jar service-${service}.jar >> nohup.out 2>&1 &";
} | ssh -tt root@${server}
done

或者如果您更喜欢heredoc:

for service in ${services[@]}
do
ssh -tt root@${server} <<EOF
    pkill -f service-${service}
    nohup java -jar service-${service}.jar >> nohup.out 2>&1 &
EOF
done