Terminate a process from linux terminal by name - ssh

Let’s say we want to end the process ssh in another terminal because the connection is frozen due to network disconnect.
To do this, we need to identify the id of the ssh process, and end the process.
We will use:

  • pipes (|) to redirect the output of one program to the next.
  • ps ax to list all processes in all terminals
  • grep to search for the ssh text in the output of the ps command
  • awk to print the first word {print $1} of the first line NR==1
  • kill command to end the process identified in the awk line

To explain the concept of pipes (|): we execute ps ax to list all processes, and with the | we pass the resulting output to the grep command, which searched for the word ssh:

~/my_project$ ps ax|grep ssh
1036743 pts/0    S+     0:00 ssh user@x.y.z.t -p 123 -i /path/to/keypair.pem
1058145 pts/1    S+     0:00 grep --color=auto ssh

This is the one-liner to end the ssh process, with grep:

ps ax|grep ssh|kill $(awk 'NR==1{print $1}')

We can use cut:

  • we search for the word ssh, excluding the grep process
  • -d ' ' - the delimiter between fields returned by ps is space - ' '
  • -f1 - selects the first match of the first field (we only have one match, if there is only one ssh process
$ kill $(ps ax | grep '[s]sh' | cut -d' ' -f1)