0

Thanks to the answer of anubhava here (https://stackoverflow.com/a/32873200/12365630) we know how to search inside an array if there is another element not like the rest of them, so i tried something similar to find out it does not work.

example, all elements should be UP, if one (or more) is not then give a message

$ arr=(UP DOWN UP UP)
$ [[ " ${arr[*]} " == *" "[^U]" "* ]] && echo "array has non-UP element(s)" || echo "no"
no

it should state that there is an non-UP (second, that DOWN) element in that array but it fails. probably it matches only letters and not words..

how should that part "[^U]" be to get this fixed?

also it would be nice to understand this better, can someone explain in detail this whole part *" "[^U]" "* ?

4

1 回答 1

0

In order for this solution to work, you have to first use the command shopt -s extglob to enable extended globbing:

[[ " ${arr[*]} " == *" "!(@(UP|*" "*))" "* ]] && echo "array has non-UP element(s)" || echo "no"

Essentially what this does is it puts a space around every element and checks to see if they match a glob. ${arr[*]} is every element in the array joined by spaces, and " ${arr[*]} " puts two more spaces around the array, so it ends up looking like " UP DOWN UP UP ". The glob checks to see if the string has any amount of text (*), followed by a space (indicating the start of an element), followed by something that's not !(...) "UP" or (@(...|...)) anything with a space.

于 2020-07-15T11:46:22.640 回答