1
arr=( d d d a)

The code below is supposed to check if it contains d. Is there a similar way to check if it contains anything else than d?

if [[ " ${arr[*]} " == *" d "* ]]; then                                         
 echo "arr contains d"  
fi
6
  • @iamauser, in your edit you altered the code presented in the question. To be sure, the original code did not work, but the revised code is not altogether correct either (it can return a false positive if the array contains ' d', 'd ', or ' d '). That aspect of your edit was not appropriate. Commented Sep 30, 2015 at 18:15
  • 1
    @JohnBollinger The formatting obscured the actual code in the original question. The edit is valid. Commented Sep 30, 2015 at 18:16
  • I just make it coded. How can I undo it ? Commented Sep 30, 2015 at 18:17
  • 1
    @iamauser, my bad. I failed to look at the markdown view of the edit. It's fine. Commented Sep 30, 2015 at 18:18
  • But in any case, the original code is indeed flawed. Commented Sep 30, 2015 at 18:19

2 Answers 2

2

You can loop over the array and check each element. There might be a better method than the following, but this one should work :

# Loop over the array elements
for i in "${arr[@]}"; 
do 
  # Check if it is not d
  if [[ "$i" != "d" ]]; then 
    echo "array element is not d. it is $i"; 
  fi 
done
Sign up to request clarification or add additional context in comments.

1 Comment

Is there anyway possible to do this without a loop? I just want to know if anywhere in the array there is an element that does not equal "d". Don't need to know which element or what it equals. Just need to know that there is an instance that does not equal "d". Thanks
0

As long as you're not using space in Array elements you can use:

[[ " ${arr[*]} " == *" "[^d]" "* ]] && echo "array has non-d element" || echo "no"

Testing:

arr=(d d d a)
[[ " ${arr[*]} " == *" "[^d]" "* ]] && echo "array has non-d element" || echo "no"
array has non-d element

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.