I have following script which is supposed to solve the problem from the title, but obviously it isn't working to assign the values to the keys. Is the reason an accidental error or is there a substantial mistake in the script?
The foldernames are names of gem-files like gem-file-foo-1.2.3
The key is supposed to be gem-file-foo
in this example and the value(s) the version number 1.2.3
or a string of multiple version numbers if there are multiple versions of the same gem.
It doesn't output any keys with echo "${!my_gems[@]}"
... why not?
#!/bin/bash
directory=$GEM_HOME/gems
declare -A my_gems
get_gemset_versions () {
last_key=""
values=""
FIND_RESULTS=$(find $directory -maxdepth 1 -type d -regextype posix-extended -regex "^${directory}/[a-zA-Z0-9]+([-_]?[a-zA-Z0-9]+)*-[0-9]{1,3}(.[0-9]{1,3}){,3}$")
printf "%s\n" $FIND_RESULTS | sort |
while read -r line; do
line=${line##*/}
KEY="${line%-*}"
VALUE="${line##*-}"
if [[ $last_key -eq "" ]]; then
last_key=$KEY
fi
if [[ $last_key -eq $KEY ]]; then
values="$values ${VALUE}"
else
values="${VALUE}"
last_key=$KEY
fi
my_gems[$KEY]=$values
done
echo "${!my_gems[@]}"
}
get_gemset_versions
Also, the logic with $last_key
and $key
to summerize equal gem-packages seems to be faulty. This is not necessarily part of the question, but it would be nice if you would point out if I am applying some faulty logics here.
Thanks
-eq
is an integer equality operator; string equality is=
(POSIX) or==
(bash extended test) – steeldriver May 29 '21 at 12:41$my_gems[key]
happened just locally and isn't available anymore after the while loop ??? – von spotz May 29 '21 at 13:33printf "%s\n" $FIND_RESULTS | sort
in a variable such that I can use the redirecting syntax to give input to thewhile
loop? Or how I can manipulate the process substitution syntax to sort the result-set offind
(see the second solution here https://stackoverflow.com/a/67739521/4307872) ? – von spotz May 29 '21 at 13:51$(...)
is command substitution, not process substitution which is a different thing.) – ilkkachu May 29 '21 at 13:53while IFS= read -r line; do <whatever>; done < <(find <whatever> | sort)
. Best practice would make the whole thing null terminated to work with all legal filenames i.e.find <whatever> -print0
/sort -z
/read -d ''
– steeldriver May 29 '21 at 13:56lastpipe
and process substitution. :) But then they're not standard features. – ilkkachu May 29 '21 at 14:08