Using heredoc to execute multi-line commands on a remote machine. Trying to get pid of a server to kill that server located in the remote machine


read -p "For HOST RESTART press 1" num
if [ "$num" == "1" ]
    ssh -t -t $HOST_IP << 'EOSSH'
    line=$(pgrep -f host_server1)
    echo $line
    sudo kill -9 "${arr[1]}"

Error : kill: (15015) - Operation not permitted

  • kill $line doesn't work ?
    – Archemar
    Jul 26, 2016 at 13:42
  • Does the kill work when you execute it manually, rather than as part of the script? Also, I'd recommend against kill -9. Use a normal kill. kill -9 is the last resort, because it doesn't allow a clean shutdown of the process. kill -9 is probably the most well known bad practice in systems administration. Jul 26, 2016 at 14:27
  • Can you start an interactive shell on the remote machine? If so, try running the commands one at a time to see the output of each, and work out which one is misbehaving.
    – JigglyNaga
    Jul 26, 2016 at 14:32
  • @JigglyNaga Tried all the commands individually on those machines and they run smoothly
    – Rohan Gala
    Jul 27, 2016 at 4:57
  • @Score_Under Yes kill is working good
    – Rohan Gala
    Jul 27, 2016 at 5:00

1 Answer 1


Since you have pgrep it is highly likely that you also have pkill.

Using pgrep and then kill introduces a theoretical race condition. Using pkill removes the race condition (from the script), and also avoids having to use a variable to hold the PIDs:

ssh -t -t "$HOST_IP" pkill -f host_server1

or, if you wanted to send the KILL signal:

ssh -t -t "$HOST_IP" pkill -KILL -f host_server1

Note that with -f, pgrep and pkill will match the pattern against the whole command line, not just the process name.

With -n and -o, the newest or the oldest (respectively) of the matching processes will be affected. Thus, if you want to KILL the newest host_server1 and nothing else:

ssh -t -t "$HOST_IP" pkill -KILL -n -f host_server1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .