2013-11-09 201 views
1

我需要帮助,了解如何将bash变量与特定格式进行比较。比较bash变量

我会读与读命令用户输入

for example: 
MyComputer:~/Home$ read interface 
eth1 
MyComputer:~/Home$ echo $interface 
eth1 

现在,我需要检查,如果“$接口”变量与IF环(它应该有“ETH”中开始,并应包含数字0-9) :

if [[ $interface=^eth[0-9] ]] 
then 
    echo "It looks like an interface name" 
fi 

在此先感谢

回答

3

您可以使用正则表达式是:

if [[ $interface =~ ^eth[0-9]+$ ]] 
then 
    ... 
fi 
+0

我可以在'if [[$ interface =〜^ eth [0-9] + $]]'中理解^然而您能否解释在$ bash中使用〜和+ $ – Rockwire

+0

这是一个正则表达式。 '=〜'是匹配的运算符,'+'表示前一个'[]'中的内容应该出现1次或多次。我认为'[[]]'风格不是可移植的,所以应该避免这种情况?! – EverythingRightPlace

+0

谢谢你的回答 – Rockwire

0

你可以使用bash的V3 +运营商=~安德鲁Logvinov说:

[[ $interface =~ ^eth[0-9]+$ ]] && # ... 

或者:

if [[ $interface =~ ^eth[0-9]+$ ]]; then 
    # ... 
fi 

否则,你可以使用太多egrepgrep -E(这是与旧炮弹像SH有用...):

echo "$interface"|egrep "^eth[0-9]+$" > /dev/null && # ... 

或者:

if echo "$interface"|egrep "^eth[0-9]+$" > /dev/null; then 
    # ... 
fi 
1

你可以使用bash的水珠此:

if [[ $interface = eth+([[:digit:]]) ]]; then 
    echo "It looks like an interface name" 
fi 

(避免正则表达式删除一个问题)。哦,并且介意=标志周围的空间,以及[[]]之前和之后的空格。