2013-03-09 89 views
1

我希望能够验证在bash脚本中是否有IP形式的东西,并且我在网上发现了各种代码片段......它们都有相同的结构..BASH测试错误[[]]

#!/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 

反正我收到以下错误

./script.sh: 18: ./script.sh: [[: not found 

我不明白为什么我无法完成这个测试...任何帮助,将不胜感激。

我打电话与

sudo ./script.sh 

剧本,我相信使用sudo是造成这个问题的,但我需要须藤PFOR我的剧本的其他部分。

+1

嗯,您提供的代码段适用于我。你确定这是错误的第18行吗? – 2013-03-09 23:37:39

+0

哪个bash版本? – Kent 2013-03-09 23:38:05

+0

你怎么称呼这个scipt? – choroba 2013-03-09 23:38:15

回答

1

虽然[[ ... ]]测试自第一版本开始([[ ... ]]取自Kornshell),但在BASH版本中可能存在一些Bourne shell兼容性设置。但是,我唯一能做的就是编译BASH,而不需要--enable-cond-command。试试打字:

$ /bin/bash -c help 

这将打印出一堆各种帮助选项。旁边有星号的意味着你的BASH版本没有启用内置命令。

最后,你可能需要找到这个建在一个替代...

试试这个:

if echo "$ip" | egrep -q "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" 

注意不要使用方或双方括号可言。

-q选项可确保egrep命令不会打印出任何内容。相反,如果模式匹配,它将返回0,否则返回1.这将与if命令一起使用。这是我们在直接Bourne shell的日子里使用它的方式,其中正则表达式没有内置到shell中,而且我们不得不用石头凿出shell脚本,并且拥有真正的VT100终端。

顺便说一下,在您的正则表达式中,500.600.700.900仍然会显示为有效的IP地址。

+0

或者,也许,不知何故,你没有使用预期的shell ...而不是你的命令行shell支持'[[';没有[[内置的]较弱的shell会尝试查找[[可执行文件。 – Gilbert 2013-03-10 01:22:28

+0

@Gilbert这可能是真的,但OP有'#!/bin/bash'在他的程序的第一行应该指定'bash' shell。我已经看到了与'/ bin/sh'链接的bash shell,并且如果将shell作为'/ bin/sh'执行,它将不会执行bash扩展。我也想过,也许OP的网站在'/ etc/bashrc'中有一些东西,它可以消除''[['',但我在'set -o'或'shopt'中找不到任何选项会导致打开或关闭特定功能。此外,如果用户明确指定'bash'作为其选择的执行shell,为什么要这样做呢? – 2013-03-10 01:48:50

+0

在我这一生中,我看到了用cp或ln重定向炮弹所做的各种奇怪的事情。不是经常的,但是当它发生时,疼痛很大。 – Gilbert 2013-04-29 22:38:11