Array from awk

I'm trying to get the output from awk into a bash array. Here is my script.

#!/bin/bash
while :
	do
	app=$( osascript -e "tell application \"System Events\" to return name of every process whose frontmost is true" )
echo "$app"
		if [[ "$app" =~ [Jj]ava ]]
			then
				ps -ax | grep -v awk | pids=( $(awk '/[Jj]ava/{print $1}') )
				echo "${pids[@]}"
		fi
	done

I haven't shown it yet here, but my plan is to iterate through the "pids" array and kill every process found. This is to keep our students from playing java games during class. Since many of these games have multiple processes associated with them, this is the only way I can see to do it. Anyway, the problem is that I get an empty array when I do this. If I just run the awk command without the variable assignment, it works properly.

I suspect the problem is that the output from the last pipe is not being passed to awk because is it inside the parentheses. Any solution or workaround for this?

---------- Post updated at 06:02 PM ---------- Previous update was at 04:55 PM ----------

Ok, I figured it out. Here is what I did in case anyone else is having this issue.

pids=( "$( ps -ax | grep -v awk | awk '/[Jj]ava/{print $1}' )" )

You should install pgrep :slight_smile: It's probably there. Try it.

Yeah, I should. But I am deploying this to 800+ machines, through a launch daemon we already have running. I don't want to add an external piece into the puzzle.

Next time we do imaging I plan to install it.

OK. The grep -v at least may not be necessary in this case since you won't find "Java" nor "java" in the awk string due to the grouping used.

If interested, the reason the first method doesn't work is that your variable assignment is done at the end of a pipeline which in bash is executed in a subshell, a child shell which cannot affect the parent. Much like trying to use cmd | read variable etc.

Yeah, I realized that about the "grep -v" as soon as I posted. It would also not match even if I just had [j] since, awk is looking for the regex as opposed to a literal [j].

I see what you mean about the subshell. So if I do this:

ps -ax | (pids=( $(awk '/[Jj]ava/{print $1}') ) ; echo "${pids[@]}")

It prints the correct pid, although I can't do anything with it since it goes away once the subshell exits.

You can. Just pipe it to xargs kill, like:

 ps ax | awk '/[jJ]ava]{print $1}' | xargs kill