<<< Back to Tips Index

19th Sept 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" doesn't 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
$

Invest in your career. Buy my Shell Scripting Tutorial today:

 

og:image credit: © https://www.flickr.com/photos/mkuram/4872078284/ CC

Steve's Bourne / Bash shell scripting tips
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon
Join the Facebook page for more tips and tricks:


Buy my Shell Scripting Tutorial

(Free Sample)
(more info)

$9.99 US Dollars

£4.99 UK Pounds

€6.99 Euros