
배열에 bash의 요소가 있는지 확인하는 좋은 방법이 있습니까(루프하는 것보다 낫습니다)?
또는 숫자나 문자열이 미리 정의된 상수 집합과 같은지 확인하는 다른 방법이 있습니까?
답변1
Bash 4에서는 연관 배열을 사용할 수 있습니다.
# set up array of constants
declare -A array
for constant in foo bar baz
do
array[$constant]=1
done
# test for existence
test1="bar"
test2="xyzzy"
if [[ ${array[$test1]} ]]; then echo "Exists"; fi # Exists
if [[ ${array[$test2]} ]]; then echo "Exists"; fi # doesn't
처음에 어레이를 설정하려면 직접 할당을 수행할 수도 있습니다.
array[foo]=1
array[bar]=1
# etc.
또는 이 방법으로:
array=([foo]=1 [bar]=1 [baz]=1)
답변2
오래된 질문이지만 아직 가장 간단한 해결책이 나오지 않은 것 같습니다 test ${array[key]+_}
. 예:
declare -A xs=([a]=1 [b]="")
test ${xs[a]+_} && echo "a is set"
test ${xs[b]+_} && echo "b is set"
test ${xs[c]+_} && echo "c is set"
출력:
a is set
b is set
이 작업이 어떻게 확인되는지 확인하려면이것.
답변3
연관 배열의 요소가 존재하는지(설정되지 않음) 테스트하는 방법이 있습니다. 이는 비어 있는 것과 다릅니다.
isNotSet() {
if [[ ! ${!1} && ${!1-_} ]]
then
return 1
fi
}
그런 다음 사용하십시오.
declare -A assoc
KEY="key"
isNotSet assoc[${KEY}]
if [ $? -ne 0 ]
then
echo "${KEY} is not set."
fi
답변4
#!/bin/bash
function in_array {
ARRAY=$2
for e in ${ARRAY[*]}
do
if [[ "$e" == "$1" ]]
then
return 0
fi
done
return 1
}
my_array=(Drupal Wordpress Joomla)
if in_array "Drupal" "${my_array[*]}"
then
echo "Found"
else
echo "Not found"
fi