RSS Feed Share on Twitter

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.

#!/bin/bash

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

NEEDLE=hello
HAYSTACK=helloworld

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

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

An example of running the script looks like this:

$ ./strstr.sh
helloworld contains hello
helloworld does not contain goodbye
$

 

 


You can buy the content of this tutorial as a PDF to download to all of your devices!

Contact

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!