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 axto list all processes in all terminalsgrepto search for thesshtext in the output of thepscommandawkto print the first word{print $1}of the first lineNR==1killcommand to end the process identified in theawkline
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 thegrepprocess -d ' '- the delimiter between fields returned bypsis space -' '-f1- selects the first match of the first field (we only have one match, if there is only onesshprocess
$ kill $(ps ax | grep '[s]sh' | cut -d' ' -f1)