How to convert multiple lines to one line in bash stdout?

I sometimes do this in my shell:

sam@sam-laptop:~/shell$ ps aux | grep firefox | awk '{print $2}'
2681
2685
2689
4645

$ kill -9 2681 2685 2689 4645

Is there a way to convert multiple lines containing a PID into one line separated by spaces? (It’s a little annoying to dial PID every time, and I really would like to know :))

Many thanks.

+5
source share
6 answers

An easy way to do this is to use xargs

ps aux | grep firefox | awk '{print $2}' | xargs kill -9

This will invoke the kill command with all pids at the same time. (Exactly what you want)

+11
source
    killall -9 firefox 
+6
source
pids=""
for pid in $(ps aux | grep firefox | awk '{print $2}')
do
pids=" $pid"
done
kill -9 $pids
+2

pkill. pgrep.

, , ?

pkill firefox

-9 pkill , ; SIGKILL:

. . , , , , . . [wlug.org]

, , SIGKILL. SIGKILL , . SIGTERM SIGINT python script, , mplayer . SIGKILL, .

SIGTERM - , kill shell. SIGINT - , (control-C). [debian.org]

+2

awk

ps -eo pid,args | awk 'BEGIN{s="kill -9 "}$2~/bash/{s=s" "$1} END{system(s)}'
+2

I agree with all the other answers about using pkill, but ... and instead of using xargs... you can skip it to tr:

kill $(ps aux | grep [f]irefox | awk '{print $2}' | tr '\n' ' ')

Also consider using [f]so that you don't match the grep process itself.

+2
source

All Articles