The Shell Scripting Tutorial


The strstr() function in Bash

This function uses Bash's pattern matching to implement the well-known strstr() function

19 Sep 2016

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
$


My Paperbacks and eBooks

My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.

Shell Scripting Tutorial

Shell Scripting Tutorial
is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion.

Also available in PDF form from Gumroad:Get this tutorial as a PDF
Shell Scripting: Expert Recipes for Linux, Bash and more

Shell Scripting: Expert Recipes for Linux, Bash and more
is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script.