Reputation: 179
I'd like to be able to validate that something is in the form of an IP in a bash script and I found various pieces of code online... they all have about the same structure..
#!/bin/bash
valid_ip()
{
local ip=$1
echo $ip
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
ret=0 # is an IP
else
ret=1 # isn't an IP
fi
return $ret
}
# SCRIPT -------------------------------------
#clear the table
ipfw table 1 flush
ips=$(dig -f ./hostnames.txt +short)
# For each of the IPs check that it is a valid IP address
# then check that it does not exist in the ips file already
# if both checks pass append the IP to the file
for ip in $ips
do
if valid_ip $ip; then
if grep -R "$ip" "~/Dropbox/ProxyBox Stuff/dummynet/ips.txt"; then
echo "$ip already exists"
else
echo $ip >> ips.txt
fi
fi
done
# get the IP's and add them to table 1
cat ips.txt | while read line; do
ipfw table 1 add $line
done
Anyway I am getting the following error
./script.sh: 18: ./script.sh: [[: not found
I can't understand why I can't complete this test... any help would be appreciated.
I call the script with
sudo ./script.sh
I believe using sudo is contributing to the problem, but I need sudo pfor other parts of my script.
Upvotes: 1
Views: 275
Reputation: 107040
Although the [[ ... ]]
test is in all versions of BASH since the first release (the [[ ... ]]
is taken from Kornshell), it is possible that there may be some Bourne shell compatibility setting in your version of BASH. However, the only thing I could turn up is compiling BASH without the --enable-cond-command
. Try typing this:
$ /bin/bash -c help
This will print out a bunch of various help options. The ones with an asterisk next to them means that your version of BASH doesn't have that builtin command enabled.
In the end, you might have to find an alternative to this built in...
Try this:
if echo "$ip" | egrep -q "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
Note that you don't use square or double square brackets at all.
The -q
option ensures that the egrep
command won't print out anything. Instead, if the pattern matches, it will return a 0, and if not, it will return a 1. This will work with the if
command. This is the way we use to do it back in the days of straight Bourne shell where regular expressions weren't built into the shell, and we had to hew shell scripts out of stone, and had real VT100 terminals.
By the way, in your regular expression, 500.600.700.900
will still show up as a valid IP address.
Upvotes: 1