I’m writing a script using multiple dialog screens in bash. One of the functions of the script should be killing specific processes. I load all my PID values in one array called pid:
pid = ('1234' '1233' '1232' '1231' '1230')
Then I present the user with a dialog checklist that contains a list of the processes.
After they select some of them dialog returns the checklist entry number, for example 0,2,4.
My initial plan was to store the selected entries in a second array and then use it to get specific PID’s from the first array, but so far, nothing I’ve tried worked, in this case that would be: 1234, 1232, 1230. So I can kill those specific processes.
Does anyone have a better solution? I want the easiest way of killing processes based on selections made by the user at the dialog checklist.
Here is the function in question:
stop_tunnel() {
local tunnels
local pid
declare -a tunnels
declare -a pid
#this is executed on a remote system in the real script
ps aux | grep -w ssh > $_temp
awk -F "ssh" '{print "ssh" $2}' $_temp > $_temp1
awk '{print $2}' $_temp > $_temp2
IFS='
'
tunnels=( $( < $_temp1 ) )
pid=( $( < $_temp2 ) )
dialog --checklist "Select tunnel to stop:" 10 72 0 \
0 "${tunnels[0]}" off \
1 "${tunnels[1]}" off \
2 "${tunnels[2]}" off \
3 "${tunnels[3]}" off \
4 "${tunnels[4]}" off \
2>$_temp
nr=$( < $_temp )
dialog --title " Tunnel stop " --msgbox "\nYou stopped these tunnels: ${nr[@]}" 6 44
}
The nr array holds the users selection. And I wanted to use that to pull specific members out of the pid array.
Select might be what you need:
Note that blanks around the assignment won’t work:
To allow to kill multiple processes in sequence:
The echo is of course just for testing.
A hint for the user, that an invalid index will terminate the process killing seems appropriate. A second approach could be an explicit termination case:
which you would handle with the break.
If you just want to iterate over the selections, being made:
update towards you comment:
I don’t have dialog installed, but I guess
zenityis similar. There you capture the output of a list seleciton: