它应该是这样的:
if [[ $string =~ $regexp ]]; then #do smthg else #do somthg else fi
所以这是我的代码,遵循这个结构,它的作用是检查SSID中包含的名称是否在iw dev wlan0链接的输出中是presend:
if [[ $(iw dev wlan0 link) =~ $SSID+ ]]; then #do sthming else echo "wrong network" fi
由于某些原因,我无法破译,如果我将它直接运行到bash shell中,这个语句非常有效
if [[ $(iw dev wlan0 link) =~ $SSID+ ]]; then echo found; else echo not found; fi
但是如果我在它包含的脚本中运行它,它会吐出来:
scripts/ssidchecker.sh: 22: [[: not found
22是“fi”关键字的行.最奇怪的是它总是会执行“else”语句中包含的代码
解决方法
首先,什么是[[?它是一个shell关键字.
samveen@maverick:~$type [[ [[ is a shell keyword
这意味着[[是bash的内部关键字,而不是命令,因此不能与其他shell一起使用.因此,您的错误输出
scripts/ssidchecker.sh: 22: [[: not found
意味着您正在使用的shell可能
>不是打击
>一个早于2.02的bash版本([[在Bash-2.02中引入)
鉴于2.02是一个非常老的版本(pre Y2K),所有这些只是指出你用来运行脚本的shell可能不是/ bin / bash,而是可能是/ bin / sh这是最常用的路径用于Bourne shell脚本shebang(#!)行.
请将其更改为/ bin / bash或显式运行bash scripts / ssidchecker.sh,你就可以了.
至于为什么总是执行else部分,从if的角度来看,[[未找到的命令与失败(非零返回值)相同).因此执行else部分.
samveen@maverick:~$/bin/whosyourdaddy -bash: /bin/whosyourdaddy: No such file or directory samveen@maverick:~$echo $? 127
作为关于可移植性的旁注,bash黑客维基也对[[关键字:
Amongst the major “POSIX-shell superset languages” (for lack of a
better term) which do have[[
,the test expression compound command is
one of the very most portable non-POSIX features. Aside from the =~
operator,almost every major feature is consistent between Ksh88,
Ksh93,mksh,Zsh,and Bash. Ksh93 also adds a large number of unique
pattern matching features not supported by other shells including
support for several different regex dialects,which are invoked using
a different Syntax from Bash’s=~
,though=~
is still supported by ksh
and defaults to ERE.