Hady Hallak
Hady Hallak

Reputation: 347

How can you search for a char in a string in bash?

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

Upvotes: 2

Views: 219

Answers (4)

Elazar
Elazar

Reputation: 21595

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

Upvotes: 2

Jens
Jens

Reputation: 72639

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

Upvotes: 3

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20843

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

[[ $var =~ "/" ]] && echo "contains a slash"

Upvotes: 8

iruvar
iruvar

Reputation: 23364

The following would work

[[ "$var" = */* ]]

Upvotes: 4

Related Questions