我卡作爲其僅僅只評估第一線。
因爲你else
塊你有exit
聲明,想如果線路不匹配,循環將被終止由於exit 1
,所以進一步的迭代不會發生。
閱讀第一行後,us-east-1-1
不等於us-east-1-3
,布爾false
,所以在你else
塊你有exit
語句,所以終止
+ 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
您可以修改像下面這樣你就會少用資源,逐行讀取,而不是讀整個文件到陣列
[[email protected] 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
輸出when cluster=us-east-1-3
[[email protected] 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
輸出when cluster=us-west-1-3
[[email protected] 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
您可以使用awk
這種類型的宗旨,合理,速度會更快
下面是一些例子
$ cat file
us-east#1-1#abcdefg1234Ad
us-west#1-3#654kjhytgr
us-east#1-4#lkjhg765
輸出(當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
輸出(當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
您可以使用「readarray arr