I'm new to bash scripting, so please bare with me as I learn here. I'm trying to audit some NetworkManger connections via a script. I'm stuck at how to get a filtered list of connection names, based on their type. More specifically, I want to have an array in the script:
declare -a FILTER
FILTER=(bond ethernet)
And then run the members of that against the command output of nmcli con show
, in order to only return connections that have a type which matches a member of the FILTER array (in the example below, that would mean 'Bond0' only). I want to store the matches in RESULTS array.
Example, nmcli con show
produces:
NAME UUID TYPE DEVICE
Bond0 akjkajfljklfa bond ifbond
Wi-Fi jkjkjjkljahjh wifi wlo
Whats the question:
How do I overcome the 'subshell processing resulting in an empty array at the end' problem, when processing command output?
What I've Tried:
So, I think I want to:
- Go line by line.
- Isolate fields 1 and 3 (Name and Type) from the command output.
- Compare field 3 for each line against the FILTER array.
- Store field 1 in RESULTS, if field 3 matches against a FILTER array member.
I've tried piping nmcli output into IFS= -r line; do
and the passing $line
to awk in various ways, then loading array -a RESULTS
via a bunch of different methods such as in a loop and also using mapfile -t RESULS < <(command substitution)
etc.
Whilst I can get to a point with all methods where it looks like the line used for loading matches into the RESULTS array (set -x
showing it returning the correct names and loading them into the array), when I get out of whatever mechanism I have used to load the RESULTS array, it is always empty when I echo ${RESULTS[@]}
with a length of 0.
I don't have all the code that I have tried, but roughly speaking, here's part of my latest fail (sorry, had to retype all this on a different machine to post this question, hence not all of it as there is a lot more in the script):
declare -a FILTER
FILTER=(bond ethernet)
declare -a RESULTS
nmcli con show | while IFS= read -r line
do
# A bunch of if's and so forth to to filter the right things, example: #
if [[ " ${FILTER[@]} " =~ " $(echo $line | awk {`print $3`} "]]; then
mapfile -t RESULTS < <(nmcli con show | while IFS= read -r line; do echo $line | awk '{print $1}`)
fi
done
echo ${RESULTS[@]}
I'm obviously doing something wrong as it relates to processing results in subshells, thinking i'm loading the array, but then stepping outside the subshell and it disappears.