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?
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:
Or even better is if you check the return code of grep in your if-condition:
You can also do away with the
grepand use this instead: