0

Having some issues checking whether the hostname of the current host matches a whitelist and running an if statement that only runs if the host matches the whitelist and an application is installed. Here's what I have.. where am I going wrong? It's always returning exit 1 no matter what.

#!/bin/bash

WHITELIST=(host1 host2 host3)

printf -- '%s\n' "${WHITELIST[@]}" | grep $HOSTNAME

if [ -e "/Applications/myapp.app" ] && [ $? = 1 ];
then
    echo "myapp exists and hostname doesn't match whitelist"
    exit 0
else
    echo "myapp doesn't exist or hostname matches whitelist"
    exit 1
fi
tripleee
  • 175,061
  • 34
  • 275
  • 318
Jimmy W
  • 3
  • 5
  • Does this answer your question? [Check if a variable exists in a list in Bash](https://stackoverflow.com/questions/8063228/check-if-a-variable-exists-in-a-list-in-bash) – Nic3500 Nov 08 '21 at 05:08

1 Answers1

0

The immediate problem is that $? is the result of [ -e "/Applications/myapp.app" ]. You'll want to avoid the antipattern anyway; see Why is testing “$?” to see if a command succeeded or not, an anti-pattern?

I'm guessing you also want to avoid using the host name as a regular expression for grep (add -F), or check whether it's a substring of anything on the whitelist (add -x to match whole lines only).

Tangentially, avoid upper case for your private variables.

#!/bin/bash

whitelist=(host1 host2 host3)

if [ -e "/Applications/myapp.app" ] &&
    ! printf -- '%s\n' "${whitelist[@]}" | grep -xF "$hostname"
then
    echo "myapp exists and hostname doesn't match whitelist"
    exit 0
else
    echo "myapp doesn't exist or hostname matches whitelist"
    exit 1
fi

The -- in printf isn't strictly necessary, since you are in complete control over the format string, and it doesn't start with a dash.

Ideally, you'd probably want to avoid using an external process (grep) for anything the shell can handle natively; see also Check if a variable exists in a list in Bash

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks - all of your points make a lot of sense. Unfortunately it still doesn't look like it's working, I'm getting exit 1 each time even if I change the whitelist. I'll keep working on it and see what I can do - any more ideas? – Jimmy W Nov 08 '21 at 22:40
  • I've narrowed it downto the printf statement + grep. If I remove that out then the exit codes work as expected. – Jimmy W Nov 08 '21 at 23:44
  • Sorry, I was missing the negation; fixed now, I hope. – tripleee Nov 09 '21 at 05:31