Reputation: 369
I want to find whether a string contains a forward slash using "grep" command. It is easy at the beginning, and I wrote the following script.
foo=someone/books
if [ `echo "$foo" | grep '/'` ]
then
echo "has forward slash"
fi
however, the problem is in the corner, if I set the variable "foo" to the following string,
foo="someone/books in stack"
The above script will be failed since there is "space" in variable foo, when the command expands, the condition in if statement is as below.
grep '/' someone/books in stack
Because of "space", the above "grep" command has too many arguments that is illegal. FYI, I try to solved this problem using case statement:
case $foo in
*/*)
echo "has forward slash"
;;
*)
;;
esac
However, I do not want to use case statement since it's verbose. So how could I solved this problem using grep command or others?
Upvotes: 0
Views: 2389
Reputation: 247162
There's nothing wrong with being verbose -- it often aids maintainability. However, you can terse it up: You don't need every newline, nor do you need the default branch if you do nothing in it.
case "$foo" in
*/*) echo "has forward slash" ;;
esac
If you insist on using grep, use the return status from it and not the output:
if echo "$foo" | grep -q /; then
echo "has forward slash"
fi
Upvotes: 0
Reputation: 1943
foo="someone/books with spaces"
bar=`echo $foo | grep '/'`
if [ $? -eq 0 ]
then
echo "$foo has forward slash"
fi
This works for me.
If you don't want to resort to using exit status this way, I suggest you take a look at dogbane's reply for a more correct answer.
Upvotes: 0
Reputation: 274828
You are not using the if-statement correctly. The command in the if-condition needs to be quoted so that it becomes a single string when expanded. Like this:
if [ "`echo "$foo" | grep '/'`" ]
then
echo "has forward slash"
fi
Or even better is if you check the return code of grep in your if-condition:
if $(echo "$foo" | grep -q '/')
then
echo "has forward slash"
fi
You can also do away with the grep
and use this instead:
foo="someone/books in stack"
if [[ "$foo" == */* ]]
then
echo "has forward slash"
fi
Upvotes: 2