它似乎是一种比较运算符,但它究竟是什么呢?以下代码(取自https://github.com/lvv/git-prompt/blob/master/git-prompt.sh#L154)?
if [[ $LC_CTYPE =~ "UTF" && $TERM != "linux" ]]; then
elipses_marker="…"
else
elipses_marker="..."
fi
我目前正在尝试让git-prompt
在MinGW下运行,而MinGW提供的shell似乎不支持此运算符:
conditional binary operator expected
syntax error near `=~'
` if [[ $LC_CTYPE =~ "UTF" && $TERM != "linux" ]]; then'
在这种特定情况下,我可以用elipses_marker="…"
替换整个块(因为我知道我的终端支持unicode),但这个=~
究竟是什么呢?
答案 0 :(得分:10)
这是对内置[[
命令的仅限bash的补充,执行正则表达式匹配。由于它不必与完整字符串完全匹配,因此符号会被挥动,以表示“不精确”匹配。
在这种情况下,如果$LC_CTYPE
CONTAINS 字符串为“UTF”。
更便携版:
if test `echo $LC_CTYPE | grep -c UTF` -ne 0 -a "$TERM" != "linux"
then
...
else
...
fi
答案 1 :(得分:6)
这是正则表达式匹配。我猜你的bash版本还不支持。
在这种特殊情况下,我建议用更简单(和更快)的模式匹配来替换它:
[[ $LC_CTYPE == *UTF* && $TERM != "linux" ]]
(请注意,此处不得引用*
)
答案 2 :(得分:3)
与Ruby一样,它匹配RHS操作数是正则表达式的位置。
答案 3 :(得分:2)
它匹配正则表达式
请参阅http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF
中的以下示例#!/bin/bash
input=$1
if [[ "$input" =~ "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" ]]
# ^ NOTE: Quoting not necessary, as of version 3.2 of Bash.
# NNN-NN-NNNN (where each N is a digit).
then
echo "Social Security number."
# Process SSN.
else
echo "Not a Social Security number!"
# Or, ask for corrected input.
fi