baku
baku

Reputation: 775

bash script: parsing grep command output and passing to second action

docker-compose down 

sometimes crashes, leaving behind busy resources which prevent fully unmounting and remounting docker volumes

i can manually fix this by doing something like:

grep -l 12c8b1e0d711db12b /proc/*/mountinfo    

which gives:

/proc/12053/mountinfo
/proc/16127/mountinfo
...
/proc/16139/mountinfo
/proc/16192/mountinfo

etc

where each number is the process PID now i can do

kill -9 16139 12053 ... 16139

I'm trying to put this into a bash script to help automate this process.

Question: I need to pass the output of grep command through the correct regex to parse out the 2nd argument (the int value in each line of /proc/16192/mountinfo). The I need to assemble these into a space separated string, and finally pass this string as argument to kill.

I'm not really sure how to approach this in bash scripting

Any and all pointers welcomed

Upvotes: 1

Views: 2147

Answers (2)

Ed Morton
Ed Morton

Reputation: 203645

Whenever you find yourself wanting to parse the output of grep, sed, etc. you should really consider just using awk instead.

procs=$(awk '/12c8b1e0d711db12b/{split(FILENAME,f,"/"); print f[3]}' /proc/*/mountinfo)
[ -n "$procs" ] && kill -9 "$procs"

Upvotes: 0

apatniv
apatniv

Reputation: 1856

You can use straight up bash scripting with parameter substitution to extract the process id and put them in an array and then use kill on it.

For example:

declare -a process
for t1 in $(grep -l 12c8b1e0d711db12b /proc/*/mountinfo); do
   t2="${t1#/proc/}" # remove /proc/ from beginning
   pid="${t2%/mountinfo}" # remove /mountinfo from the end
   process+=("$pid")
done

kill -9 "${process[@]}"

Upvotes: 4

Related Questions