Find the PID(s) of running processes and store as an array

前端 未结 4 1454
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 03:01

I\'m trying to write a bash script to find the PID of a running process then issue a kill command. I have it partially working, but the issue I face is that there may be mor

4条回答
  •  鱼传尺愫
    2021-01-12 03:23

    You don't need to use an array if you're going to immediately iterate over the results and perform an action:

    for pid in $(ps -fe | grep '[p]rocess' | grep -v grep | awk '{print $2}'); do
        kill "$pid"
    done
    

    Notice we have to exclude grep's pid from the list of processes to kill. Or we could just use pgrep(1):

    for pid in $(pgrep '[p]rocess'); do
        kill "$pid"
    done
    

    If you actually needed to store the pids in an array, pgrep is how you would do it:

    pids=( $(pgrep '[p]rocess') )
    

    Back to killing process. We can still do better. If we're just using pgrep to get a list of processes to kill them, why not go straight for pgrep's sister program: pkill(1)?

    pkill '[p]rocess'
    

    As it turns out, no need for bash scripting at all.

提交回复
热议问题