I'm stuck as its just evaluating the first line only.
Because in your else
block you have exit
statement, suppose if line does not match, loop will be terminated due to exit 1
, so further iteration will not take place.
After reading first line, us-east-1-1
is not equal to us-east-1-3
, Boolean false
, so in your else
block you have exit
statement, so termination
+ cluster=us-east-1-3
+ KEY=./file
+ IFS='#'
+ arr=($(< $KEY))
+ declare -a arr
+ [[ us-east-1-1 == us-east-1-3 ]]
+ echo 'No match'
No match
+ exit 1
You can modify like below so that you will use less resource, read line by line instead of reading entire file into array
[akshay@localhost tmp]$ cat t.sh
#!/usr/bin/env bash
set -x
cluster="$1"
while IFS=# read -r field1 field2 restother; do
if [[ "$field1-$field2" == $1 ]]; then
echo "We have a match"
else
echo "No match"
fi
done < "file"
set +x
Output when cluster=us-east-1-3
[akshay@localhost tmp]$ bash t.sh us-east-1-3
+ cluster=us-east-1-3
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-1 == us-east-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-west-1-3 == us-east-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-4 == us-east-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ set +x
Output when cluster=us-west-1-3
[akshay@localhost tmp]$ bash t.sh us-west-1-3
+ cluster=us-west-1-3
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-1 == us-west-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-west-1-3 == us-west-1-3 ]]
+ echo 'We have a match'
We have a match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-4 == us-west-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ set +x
You can use awk
for this type of purpose, reasonably faster too
Here is some example
$ cat file
us-east#1-1#abcdefg1234Ad
us-west#1-3#654kjhytgr
us-east#1-4#lkjhg765
Output (when cluster="us-east-1-3"
)
$ awk -F'#' -v cluster="us-east-1-3" '{ print (cluster==$1"-"$2)? "We have a match": "No match"}' file
No match
No match
No match
Output (when cluster="us-west-1-3"
)
$ awk -F'#' -v cluster="us-west-1-3" '{ print (cluster==$1"-"$2)? "We have a match": "No match"}' file
No match
We have a match
No match