shell 脚本和正则表达式
#!bin/bash
echo enter your password :
read password
passlength=$(echo ${#password})
if [ $passlength -le 8 ];
then
echo you entered correct password
else
echo entered password is incorrect
fi
if [[$password == [a-z]*[0-9][a-z]*]];
then
echo match found
else
echo match not found
fi
我不明白这段代码有什么问题。如果我输入任何字符串作为密码,比如说 hello123
,它会给我一个错误:
hello123:找不到命令
我的脚本有什么问题?
#!bin/bash
echo enter your password :
read password
passlength=$(echo ${#password})
if [ $passlength -le 8 ];
then
echo you entered correct password
else
echo entered password is incorrect
fi
if [[$password == [a-z]*[0-9][a-z]*]];
then
echo match found
else
echo match not found
fi
I am not getting what's wrong with this code. If I enter any string as a password, let's say hello123
, it gives me an error:
hello123 : command not found
What is wrong with my script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以执行以下操作,使其与任何基于 bourne shell (/bin/sh) 的 shell 跨平台工作,没有 bash 特定的原语 -
也可以随意在变量名称周围使用
引号
。它将为您节省大量无用的调试时间。 :)You can do the following to make it work cross-platforms with any the bourne shell (/bin/sh) based shell, no bash specific primitives -
Also feel free to use
quotes
around the variable names. It will save you hours and hours worth of useless debugging. :)从技术上讲,它应该给你一个类似
[[hello123 : command not found
的错误。问题是
[[$password
没有按照您想象的方式扩展。 Bash 首先会将$password
变量解析为您输入的内容(即hello123
)。这将产生字符串[[hello123
],然后 bash 将尝试调用该字符串(并失败,因为没有任何具有该名称的内容)。只需在
[[
后面添加一个空格 (),bash 就会将
[[
识别为要运行的命令(尽管它是内置命令)。Technically it should give you an error like
[[hello123 : command not found
.The issue is that
[[$password
is not expanded how you think it is. Bash will first resolve the$password
variable to what you entered (i.e.hello123
). This will yield the string[[hello123
which bash will then try to invoke (and fail, as there is nothing with that name).Simply add a space (
) after
[[
and bash will recognise[[
as the command to run (although it is a builtin).更正后的脚本如下。错误是:
#!/bin/bash
,而不是#!bin/bash
passlength=${#password},而不是<代码>
passlength=$(echo ${#password})
[
或[[
The corrected script is below. The errors were:
#!/bin/bash
, not#!bin/bash
passlength=${#password}
, notpasslength=$(echo ${#password})
[
or[[
在 bash
[[
构造中,==
运算符将匹配 glob 样式模式,而=~
将匹配正则表达式。请参阅文档。In the bash
[[
construct, the==
operator will match glob-style patterns, and=~
will match regular expressions. See the documentation.更多调整示例..
More tuned example..
尝试
用以下
HTH替换行
Try to replace line
with following
HTH