RSS Feed Share on Twitter

Buy this tutorial as a PDF for only $5!

All Shell Scripting Tips

19 Sep 2016

The strstr() function

A while ago, I noticed a nifty trick in the /sbin/start_udev script written by Linux kernel developer Greg Kroah-Hartman. His code is licensed as GPLv2, so this is, also.

This uses Bash's pattern matching tools to provide a "strstr" function. From the C language man page of strstr: "The strstr() function finds the first occurrence of the substring needle in the string haystack". This doesn't do exactly that, it just tells you whether or not needle exists in haystack.


# From /sbin/start_udev by Greg KH (GPL v2 only)
# Does $1 contain $2 ?
strstr() {
  [ "${1#*$2*}" = "$1" ] && return 1
  return 0


strstr $HAYSTACK $NEEDLE && echo "$HAYSTACK contains $NEEDLE" || \
     echo "$HAYSTACK does not contain $NEEDLE"
# "helloworld" does contain "hello"

strstr $HAYSTACK $NEEDLE && echo "$HAYSTACK contains $NEEDLE" || \
     echo "$HAYSTACK does not contain $NEEDLE"
# "helloworld" doesn't contain "goodbye"
Download the script

An example of running the script looks like this:

$ ./
helloworld contains hello
helloworld does not contain goodbye



Books and eBooks


You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!

You can buy the content of this Shell Scripting Tutorial as a PDF!