Implementing strstr in Korn Shell

Neither Bash or the Korn Shell 93 (ksh93) provide a C-like strstr builtin. Here is a simple implementation of a strstr function in ksh93. The strstr function finds the first occurrence of s2 in s1. If s2 is an empty string, 0 is returned; if s2 occurs nowhere in s1, 0 is also returned; otherwise the offset to the first character of the first occurrence of s2 is returned.


function strstr
    typeset s1="$1"
    typeset s2="$2"

    if [[ ${#s2} == 0 ]]
        return 0

    typeset len=${#s1}
    typeset first=${s1%%${s2}*}x

    typeset ndx=${#first}
    if (( ndx > len ))
        return 0
    return $ndx

line="The quick brown fox jumped over the bush"

strstr "$line" "jumped"
echo "strstr index is: $?"

In general, when you declare a variable inside a function, the variable becomes local to the function that declares it. In ksh93, the only way to declare a local variable is with the typeset builtin in functions declared with the function keyword. If you assign a value to a variable without having declared it with typeset or do not use the function keyword syntax, the variable has global scope. This is because ksh93 has dynamic scoping.

Comments are closed.