Buy this tutorial as a PDF for only $5
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 $
Appreciate this site? Please consider making a donation:
Books and eBooks
My Shell Scripting books, available in Paperback and eBook formats.
![]() Shell Scripting Tutorial is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and to keep by your desk as an ever-present companion. | ![]() Shell Scripting: Expert Recipes for Linux, Bash and more is my 564-page book on Shell Scripting. The first half explains the features of the shell; the second half has real-world shell scripts, organised by topic, with detailed discussion of each script. |
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!