Check if string containts slash or backslash in Bash?

15,574

This checks if either \ or / are in the variable $string.

if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]
then
  echo "yes"
fi

Test:

$ string="hello"
$ if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]; then echo "yes"; fi
$
$ string="hel\lo"
$ if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]; then echo "yes"; fi
yes
$ string="hel//lo"
$ if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]; then echo "yes"; fi
yes
Share:
15,574
user1685565
Author by

user1685565

Updated on June 14, 2022

Comments

  • user1685565
    user1685565 about 2 years

    I'm currently trying to get my bash script checking if a string containts a "/" or a "\" but somehow I can't get it working.

    Here is what I got so far:

    if [[ "$1" == *\/* ]]; then
       ...
    elif if [[ "$1" == *\\* ]]; then
       ...
    fi
    

    Help is much appreciated! Thanks

  • ivan_pozdeev
    ivan_pozdeev almost 4 years
    No need for the surrounding *s if you use =~ instead of ==.
  • ivan_pozdeev
    ivan_pozdeev almost 4 years
    You can also write [[ "$string" == *\/* || "$string" == *\\* ]]