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 terminalsgrep
to search for thessh
text in the output of theps
commandawk
to print the first word{print $1}
of the first lineNR==1
kill
command to end the process identified in theawk
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 thegrep
process -d ' '
- the delimiter between fields returned byps
is space -' '
-f1
- selects the first match of the first field (we only have one match, if there is only onessh
process
$ kill $(ps ax | grep '[s]sh' | cut -d' ' -f1)