Function needs to be called based on its first character in a supplied string

Hi All,

I want to write a bash script in which a function needs to be called based on its first character in a supplied string. eg function "j" should be called when "jab" or "jgh" or "j" .... etc is hit. I have used complete -F in below script, however here function is invoked only when "j" is hit. Can any one help me in improving this script?


function j {
   ....
}

function m {
   ....
}

shopt   -s progcomp
complete  -F    _comp  j
complete  -F    _comp  m

thanks.

Hi,

Assuming you're using Bash as your shell, this is the ideal situation for the case statement. Consider the following example:

$ cat data.txt
Jog
mog
cat
dog
jug
Man
$ cat script.sh
#!/bin/bash

function j
{
        echo "Function J has been called with the following parameter: $1"
        return
}

function m
{
        echo "Function M has been called with the following parameter: $1"
        return
}

while read parameter
do
        echo "Considering parameter "$parameter"..."

        case "$parameter" in
                J*|j*)
                        j "$parameter"
                        ;;
                M*|m*)
                        m "$parameter"
                        ;;
        esac
done < data.txt

$ ./script.sh
Considering parameter Jog...
Function J has been called with the following parameter: Jog
Considering parameter mog...
Function M has been called with the following parameter: mog
Considering parameter cat...
Considering parameter dog...
Considering parameter jug...
Function J has been called with the following parameter: jug
Considering parameter Man...
Function M has been called with the following parameter: Man
$ 

Here the script reads all the parameters one at a time from the file data.txt , and if they start with a lower- or upper-case J or M the appropriate function is called. If the parameter under consideration starts with any other character whatsoever, no function is called, and the script moves right on to the next parameter in the file, continuing in this manner until it reaches the end.

Hope this helps !