John
John

Reputation: 25333

BASH Check if exists within variable

I am working on a script that will be used to map network drives. However, we only want to attempt to map the drive if the machine has a particular IP address. Listed below is a code snippet that we are trying to get working.

#!/bin/sh

IP="dig $HOSTNAME +short"

if [ $IP == *10.130.10.* ]; then
    mount drive commands here
fi

if [ $IP == *10.130.11.* ]; then
    mount drive commands here
fi

I am not able to get the check for IP to work. Is there a better way to check to see if a variable contains a string, in this case part of an IP address?

The information listed in this posting was not helpful since it did not work.

Upvotes: 1

Views: 698

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125798

You have a "bash" tag on the question, but the shebang says /bin/sh. Which do you actually want to use?

Actually, first things first. The way you're setting IP doesn't work, since it never runs the dig command; you need either backquotes or $( ) to do that:

IP="$(dig $HOSTNAME +short)"

Now, for the test; there are a number of ways to do it. This should work in all shells:

case "$IP" in
    *10.130.10.*)
        mount drive commands here
        ;;
    *10.130.11.*)
        mount drive commands here
        ;;
esac

Note that if the mount commands are the same for the two subnets, you can use *10.130.10.*|*10.130.11.*) as the pattern to match.

If you're actually using bash, you can use its [[ ]] conditional expression to do the matching more like how you had it:

if [[ "$IP" == *10.130.10.* ]]; then
    mount drive commands here
elif [[ "$IP" == *10.130.11.* ]]; then
    mount drive commands here
fi

As above, if the mount commands are the same, you can do a single conditional with if [[ "$IP" == *10.130.10.* || "$IP" == *10.130.10.* ]]; then. Also, the double-quotes around $IP aren't actually necessary in this particular case, but I always make a habit of double-quoting variables unless there's a reason not to.

Upvotes: 3

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143091

[[ "${IP/10.130.10./}" = "$IP" ]] || mount

Upvotes: 1

Related Questions