简体   繁体   中英

Multiple if conditions bash

So I need an if statement with 2 conditions:

if [[ $(cat /etc/hosts.deny 2>/dev/null) != *"ALL"* ]]; then
if [[ $(cat /etc/hosts.allow 2>/dev/null) != *"123.123.123.123"* ]]; then

If both conditions are correct it should echo an IP in /etc/hosts.allow. I tried to set both strings in 1 line with && between but that doesn't work for some reason. Is anyone able to point out what I did wrong?

Don't use cat for this; just use grep :

if grep -qvF 'ALL' /etc/hosts.deny && grep -qvF '123.123.123.123' /etc/hosts.allow; then 
  • -q suppress the output; you don't care which lines contain the matched pattern, only that grep 's exit status is 0 or nonzero.
  • -v inverts the exit status; grep succeeds if the pattern does not match.
  • -F treats the argument as a fixed string, not a regular expression. This saves you from escaping the . to match a literal period, and is a bit more efficient.
  • && creates a list whose exist status is 0 only if both grep commands have an exit status of 0 , and further, only runs the second grep if the first grep succeeds.

As you do, use double [ to insert expression inside and && or || as logical operator

if [[ $(cat /etc/hosts.deny 2>/dev/null) != *"ALL"* && $(cat /etc/hosts.allow 2>/dev/null) != *"123.123.123.123"* ]] ; then ...

Work with bash 4.2, but not all shell.

Edit : be carefull of space between [ , if , &&

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM