Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling custom function in bash results in "Command not found" [duplicate]

Tags:

function

bash

I'm trying this to display a default helptext when no parameters are given when executing the script:

if [[ $@ ]]; then 
    do stuff
else displayHelp; 
fi

displayHelp() {
    echo "some helptext"
}

But for some reason, when executing the script on console, it says:

./myScript.sh: Line 48: displayHelp: Command not found

The same occurs when I call this function via -h parameter

like image 657
pjominet Avatar asked Dec 05 '22 17:12

pjominet


1 Answers

Functions must be defined before they can be used. So put the method before your call it:

displayHelp() {
    echo "some helptext"
}

if [[ $@ ]]; then 
    do stuff
else displayHelp; 
fi

or put your main code in another method and call this one at the end of your script:

main() {
    if [[ $@ ]]; then 
        do stuff
    else displayHelp; 
    fi
}

displayHelp() {
    echo "some helptext"
}

main "$@"
like image 52
muton Avatar answered May 14 '23 21:05

muton