Вот один из способов использования grep(1)
и if-statement
#!/usr/bin/env bash
ips_acc=accept.txt
ips_den=deny.txt
read -p "Quina IP vols comprovar? " IP
if grep -wq "$IP" "$ips_acc"; then
echo "input $IP is accepted"
elif grep -wq "$IP" "$ips_den"; then
echo "input $IP is denied"
else
echo "$P is not known!" >&2
fi
Это может быть близко к коду, который вы пытаетесь написать, я просто перевел слова, которые вы есть в вашем коде через Google.
#!/usr/bin/env bash
ips_acc=accept.txt
ips_den=deny.txt
read -rp "Quina IP vols comprovar? " IP
if grep -wq "$IP" "$ips_acc" "$ips_den"; then
echo "La $IP està acceptada explícitament"
exit 0
else
echo "La IP $IP està denegada explícitament" >&2
exit 1
fi
Он заключен в if-statement
, поэтому действие будет зависеть от состояния выхода grep.
-w
заставить PATTERN соответствовать только целым словам.
-q
подавить все обычные выходные или беззвучный.
За исходный код OP, используя for loop
, но требуется функция bash4 +, потому что mapfile
#!/usr/bin/env bash
ips_acc=accept.txt ##: Save the text files in variables
ips_den=deny.txt
mapfile -t accept < "$ips_acc" ##: save the value text files in an array.
mapfile -t deny < "$ips_den" ##: Using mapfile aka readarray.
main() { ##: Create a function named main
read -rp "Quina IP vols comprovar? " IP ##: ask and save user input
for ipfitxer in "${accept[@]}" "${deny[@]}"; do ##: loop through both accept and deny values.
if [[ $ipfitxer == "$IP" ]]; then ##: if input and values match
echo "La $IP està acceptada explícitament" ##: Print/send message that they did match
exit 0 ##: Exit the script with a zero (true) status
fi
done
echo "La IP $IP està denegada explícitament" >&2 ##: Send message to stderr if there was no match.
exit 1
}
main ##: run/execute main function.
Для этого требуется exglob.
#!/usr/bin/env bash
shopt -s extglob ##: Enable shell globbing extglob.
ips_acc=accept.txt ##: save the value text files in an array.
ips_den=deny.txt
mapfile -t accept < "$ips_acc" ##: save the value text files in an array.
mapfile -t deny < "$ips_den" ##: Using mapfile aka readarray.
both=("${accept[@]}" "${deny[@]}"); ##: merge both arrays.
pattern=$(IFS='|'; printf '%s' "@(${both[*]})") ##: Format/prepare the arrays.
read -rp "Quina IP vols comprovar? " IP ##: Read/store user input
if [[ ${IP:?You did not gave an answer!} == $pattern ]]; then ##: Test if there was a match
echo "La $IP està acceptada explícitament" ##: Print/send message that they do.
exit 0 ##: Exit gracefully with zero exit status
else
echo "La IP $IP està denegada explícitament" >&2 ##: If no match send message to stderr
exit 1 ##: Exit with 1 which is an error
fi
-
Disclamer, я не говорю на вашем родном языке.
${IP:?You did not gave an answer!}
является формой расширения параметров PE.