11

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)

Any idea, suggestion ?

Thanks

William Pursell
  • 204,365
  • 48
  • 270
  • 300
voidAndAny
  • 147
  • 1
  • 1
  • 9
  • 1
    My guess is your init system doesn't use `/bin/bash` as an interpreter, instead it will use `/bin/sh`. – ko-dos Jul 28 '09 at 12:49
  • If William's answer worked, don't forget to click the "Accept answer" button! – dbr Jul 28 '09 at 13:40

7 Answers7

8

Always quote strings.

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

if echo x"$date_alarm" | grep '*' > /dev/null; then
    ...
fi 
William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

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

Atmocreations
  • 9,923
  • 15
  • 67
  • 102
  • if [[ "$date_alarm" =~ .*\*.* ]] Don't work, but as I said the strange thing is that it doesn't work only in init context during shutdown if [[ "$date_alarm" =~ '\*+' ]] not tested Tahnks – voidAndAny Jul 28 '09 at 12:36
  • Quote the pattern: if [[ "$date_alarm" =~ ".*\*.*" ]] – bstpierre Jul 28 '09 at 15:43
1
case "$date_alarm" in
*\**)
  ...
  break
  ;;
*)
  # else part
  ...
  ;;
esac

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

reinierpost
  • 8,425
  • 1
  • 38
  • 70
1
expr "$date_alarm" : ".*\*.*"
0
if echo $date_alarm|perl -e '$_=<>;exit(!/\*/)'
then
    ...
fi
chaos
  • 122,029
  • 33
  • 303
  • 309
0

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....

voidAndAny
  • 147
  • 1
  • 1
  • 9
  • no need to call external program such as grep to do what you want. In bash, the case statement should suffice. – ghostdog74 Jul 28 '09 at 13:06
0

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

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

zigo
  • 1