加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 使用带有bash的rexep的条件语句

发布时间:2020-12-14 05:49:43 所属栏目:百科 来源:网络整理
导读:我想使用bash中的“条件正则表达式”结构,从bash的第三个版本(大约2004年)开始. 它应该是这样的: if [[ $string =~ $regexp ]]; then#do smthgelse#do somthg elsefi 所以这是我的代码,遵循这个结构,它的作用是检查SSID中包含的名称是否在iw dev wlan0链接
我想使用bash中的“条件正则表达式”结构,从bash的第三个版本(大约2004年)开始.
它应该是这样的:

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.

因此你的脚本可能会在=?上失败,即使shell支持[[,如果shell不是bash但支持[[.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读