2

If I have a string var="root/Desktop", how can I determine whether var var contains a '/' character?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Hady Hallak
  • 347
  • 4
  • 8

4 Answers4

8

Bash can match against regular expressions with =~, try:

[[ $var =~ "/" ]] && echo "contains a slash"
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
  • +1 - Yours is better than using grep. But I think using an external program has its advantages. – Elazar May 18 '13 at 22:52
4

The following would work

[[ "$var" = */* ]]
iruvar
  • 22,736
  • 7
  • 53
  • 82
3

The portable solution that works in any Bourne-heritage shell and needs no expensive forks or pipes:

 case $var in
   (*/*)   printf 'Has a slash.\n';;
   (*)     printf 'No slash.\n';;
 esac
Jens
  • 69,818
  • 15
  • 125
  • 179
2

echo "${var1}" | grep '/' should work.

Elazar
  • 20,415
  • 4
  • 46
  • 67