bash 检查字符串是否包含星号 (*)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1193658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:05:10  来源:igfitidea点击:

Check if a string contains Asterisk (*)

linuxstringbashinit

提问by voidAndAny

I want to check if my string contain one or more asterisk.

我想检查我的字符串是否包含一个或多个星号。

I have tried this :

我试过这个:

if [[ $date_alarm =~ .*\*.* ]]
then
    ...
fi

It worked when I launch directly the script, but not if this script is called during shutdown (script installed in run level 0 and 6 via update-rc.d)

它在我直接启动脚本时有效,但如果在关闭期间调用此脚本则无效(通过 update-rc.d 安装在运行级别 0 和 6 中的脚本)

Any idea, suggestion ?

任何想法,建议?

Thanks

谢谢

采纳答案by William Pursell

Always quote strings.

总是引用字符串。

To check if the string $date_alarm contains an asterisk, you can do:

要检查字符串 $date_alarm 是否包含星号,您可以执行以下操作:

if echo x"$date_alarm" | grep '*' > /dev/null; then
    ...
fi 

回答by BreizhGatch

expr "$date_alarm" : ".*\*.*"

回答by reinierpost

case "$date_alarm" in
*\**)
  ...
  break
  ;;
*)
  # else part
  ...
  ;;
esac

The syntax is, well, /bin/sh, but it works.

语法是 /bin/sh,但它有效。

回答by voidAndAny

Finally

最后

if echo x"$date_alarm" | grep '*' > /dev/null; then

did the trick

成功了

Strange thing =~ .*.doesn't work only in init context during shutdown, but work perfectly if launch in bash context....

奇怪的东西=~。*. 不仅在关机期间在 init 上下文中工作,而且如果在 bash 上下文中启动,它也能完美工作......

回答by zigo

No need to redirect stdout like others do. Use the -q option of grep instead:

无需像其他人那样重定向标准输出。请改用 grep 的 -q 选项:

if echo x"$date_alarm" | grep -q '*' ; then

if echo x"$date_alarm" | grep -q '*' ; 然后

回答by Atmocreations

what happens if you replace

如果你更换会发生什么

if [[ $date_alarm =~ .*\*.* ]]

with

if [[ "$date_alarm" =~ .*\*.* ]]

you might also want to try:

您可能还想尝试:

if [[ "$date_alarm" =~ '\*+' ]]

not sure about that one...

不确定那个...

regards

问候

回答by chaos

if echo $date_alarm|perl -e '$_=<>;exit(!/\*/)'
then
    ...
fi