-2

This is very basic but eluding me. I have an array. I am checking each element of this array to see if it starts with given character. I think it what i have written is right but not getting desired response.

My code

arr=("etpass-foo" "etpass-bar" "pass-foo" "pass-abc" "etpass-abc")
for i in "${arr[@]}"
do
     if [[ $i == et* ]]; then
          printf "$i"
     fi
done

I get below output

etpass-foo
etpass-bar
pass-foo
pass-abc
etpass-abc

What is expect is

etpass-foo
etpass-bar
etpass-abc

I have also tried below if conditions

1. if [[ $i == et* ]]; then
2. if [[ "$i" == "et"* ]]; then
3. if [[ "$i" == "et*" ]]; then

Please let me know where i am wrong?

data-bite
  • 417
  • 2
  • 5
  • 17
  • 2
    You sure you're picking up bash? Which version ? Using https://www.onlinegdb.com/online_bash_shell your code works as expected... – John3136 Sep 06 '22 at 05:27
  • 3
    This test also works as expected for me (although the `printf` doesn't, because it doesn't print a newline at the end of the string; you probably want `printf '%s\n' "$i"` or just `echo "$i"`). – Gordon Davisson Sep 06 '22 at 05:32
  • That doesn't seem like a very good duplicate, since it's about checking a string prefix in Python, not bash (although the question does mention how to do it in bash). – Gordon Davisson Sep 06 '22 at 07:08

1 Answers1

2

Try to use bashregex instead, like this:

...
if [[ $i =~ ^et.* ]]; then
    echo "$i"
fi
...
Ivan
  • 6,188
  • 1
  • 16
  • 23
  • 2
    Nice approach of using regex but make sure to anchor the regex with `^` as `^et.*`, otherwise it will match `meet` as well. – tshiono Sep 06 '22 at 06:04