比较bash变量
我需要有关如何将bash变量与特定格式进行比较的帮助 我将使用read命令读取用户输入比较bash变量,bash,Bash,我需要有关如何将bash变量与特定格式进行比较的帮助 我将使用read命令读取用户输入 for example: MyComputer:~/Home$ read interface eth1 MyComputer:~/Home$ echo $interface eth1 现在我需要检查带有if循环的“$interface”变量(它的开头应该有“eth”,并且应该包含数字0-9): 提前感谢您可以为此使用正则表达式: if [[ $interface =~ ^eth[0-9]+$ ]] then
for example:
MyComputer:~/Home$ read interface
eth1
MyComputer:~/Home$ echo $interface
eth1
现在我需要检查带有if循环的“$interface”变量(它的开头应该有“eth”,并且应该包含数字0-9):
提前感谢您可以为此使用正则表达式:
if [[ $interface =~ ^eth[0-9]+$ ]]
then
...
fi
if [[ $interface = eth+([[:digit:]]) ]]; then
echo "It looks like an interface name"
fi
您可以为此使用正则表达式:
if [[ $interface =~ ^eth[0-9]+$ ]]
then
...
fi
if [[ $interface = eth+([[:digit:]]) ]]; then
echo "It looks like an interface name"
fi
您可以使用bash V3+操作符
=~
,正如Andrew Logvinov所说:
[[ $interface =~ ^eth[0-9]+$ ]] && # ...
或:
否则,您也可以使用egrep
或grep-E
(这对于像sh…这样的旧shell很有用):
或:
您可以使用bash V3+操作符
=~
,正如Andrew Logvinov所说:
[[ $interface =~ ^eth[0-9]+$ ]] && # ...
或:
否则,您也可以使用egrep
或grep-E
(这对于像sh…这样的旧shell很有用):
或:
您可以使用bash的globs进行以下操作:
if [[ $interface =~ ^eth[0-9]+$ ]]
then
...
fi
if [[ $interface = eth+([[:digit:]]) ]]; then
echo "It looks like an interface name"
fi
(避免regexp会消除一个问题)。哦,请注意
=
符号周围的空格,以及[[
和]
前后的空格。您可以使用bash的globs来实现以下目的:
if [[ $interface =~ ^eth[0-9]+$ ]]
then
...
fi
if [[ $interface = eth+([[:digit:]]) ]]; then
echo "It looks like an interface name"
fi
(避免regexp会消除一个问题)。哦,注意
=
符号周围的空格,以及[[[/code>和]]
前后的空格,如果[[$interface=~^eth[0-9]+$]
的话,^in我能理解,^in[$interface=~^eth[0-9]+$].
但是,你能解释一下在bash中~and+$的用法吗这是正则表达式。=~
是匹配运算符,+
表示前一个[]
中的内容应该出现1次或更多次。我认为[[]]
样式是不可移植的,所以应该避免这种情况?!如果[[$interface=~^eth[0-9]+$]]我可以理解^in中的内容,但是请您解释一下~and+$在bash中的用法,这是正则表达式。=~
是匹配运算符,+
表示前一个[]
中的内容应该出现1次或更多次。我认为[[]]
样式是不可移植的,所以应该避免这种情况?!