Regex if语句中的bash正则表达式

Regex if语句中的bash正则表达式,regex,bash,Regex,Bash,我被一个脚本的错误难住了,我试图运行这个脚本来挂起我的机器。我试图在elif语句中使用正则表达式在特定时间段后挂起我的机器 #!/bin/bash echo "When would you like to suspend the machine?" read "sustime" if [ "$sustime" = "now" ] then sudo pm-suspend elif [[ "$sustime" =~ [0-9]*[smhd] ]] then time=`expr "

我被一个脚本的错误难住了,我试图运行这个脚本来挂起我的机器。我试图在elif语句中使用正则表达式在特定时间段后挂起我的机器

#!/bin/bash
echo "When would you like to suspend the machine?"
read "sustime"
if [ "$sustime" = "now" ]
then
    sudo pm-suspend
elif [[ "$sustime" =~ [0-9]*[smhd] ]]
then
    time=`expr "$sustime" : '\([0-9]+)\)'`
    ttype=`expr "$sustime" : '.*\([smhd]\)'`
    sudo sleep $time$ttype ; sudo pm-suspend
else
    echo "Please enter either [now] or [#s|m|h|d]"
fi
代码在
elif
行不起作用,例如,如果我输入5s,脚本的输出是:

$ sh dbussuspend.sh 
When would you like to suspend the machine?
5s
dbussuspend.sh: 10: dbussuspend.sh: [[: not found
Please enter either [now] or [#s|m|h|d]

但是,应该是我输入了字符串
5s
elif
下运行代码块。实际上,我已经尝试了任何正则表达式来代替
[0-9]*[smhd]
,但都有相同的错误

此问题不是由脚本引起的,而是由调用脚本的方式引起的:

sh dbussuspend.sh
应该是:

bash dbussuspend.sh
bash
知道如何
[[
,但是
sh

更好的是,按照建议去做。做一次:

chmod +x dbussuspend.sh
然后,像这样调用:

./dbussuspend.sh
此外,请询问您对
expr
的使用,以及您的
bash
regex.GNU coreutils
sleep
的支持,例如
sleep 30s
sleep 2m
sleep 1h
。使用
man sleep
在您的系统上检查此项。如果是,则此项工作正常:

elif [[ "$sustime" =~ ^[0-9]+[smhd]$ ]]
then
    sudo sleep $sustime ; sudo pm-suspend

^[0-9]+[smhd]$
中的
^
$
来匹配字符串的开头和结尾并防止匹配,例如“uzeifue1sziufzr”)

此问题不是由脚本引起的,而是由您调用它的方式引起的:

sh dbussuspend.sh
应该是:

bash dbussuspend.sh
bash
知道如何
[[
,但是
sh

更好的是,按照建议去做。做一次:

chmod +x dbussuspend.sh
然后,像这样调用:

./dbussuspend.sh
此外,请询问您对
expr
的使用,以及您的
bash
regex.GNU coreutils
sleep
的支持,例如
sleep 30s
sleep 2m
sleep 1h
。使用
man sleep
在您的系统上检查此项。如果是,则此项工作正常:

elif [[ "$sustime" =~ ^[0-9]+[smhd]$ ]]
then
    sudo sleep $sustime ; sudo pm-suspend

^
$
^[0-9]+[smhd]$
中匹配字符串的开头和结尾并防止匹配,例如“uzeifue1sziufzr”)

旁注:您可能需要
[0-9]+[smhd]
否则
h
将是可接受的输入。您不需要
expr
;您可以在原始正则表达式中使用捕获组,然后从数组
BASH\u REMATCH
访问捕获的值。旁注:您可能需要
[0-9]+[smhd]
否则
h
将是一个可接受的输入。您不需要
expr
;您可以在原始正则表达式中使用捕获组,然后从数组
BASH\u REMATCH
访问捕获的值。也不要使用
expr
。特别是当您似乎正在这样做时,以拆分输入,然后将其放入立即重新组合。比显式使用
bash
更好的是,您应该使用
chmod+x dbussuspend.sh
使脚本可执行(如果它还没有),然后使用
/dbussuspend.sh
运行它,这样它将遵守shebang行(它已经是
/bin/bash
,应该是这样的).Omg我喜欢这个网站。非常感谢所有人,真的为我清理了它。也不要使用
expr
。特别是当看起来你这样做是为了分割输入,然后立即将其重新组合在一起。即使比显式使用
bash
更好,你也应该让脚本可执行(如果它还没有执行的话)使用
chmod+x dbussuspend.sh
,然后使用
/dbussuspend.sh
运行它,这样它就会遵守shebang行(它已经是
/bin/bash
,应该是这样)。天哪,我喜欢这个网站。非常感谢大家,真的为我清理了它。