Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Requiring One and Only One Argument In A Bash Function

This is an example function you can add to your .rc files that requires exactly one argument to run. It checks to make sure there's an argument in slot `$1` otherwise it bails. Once it's past that check, it checks to see if an extra argument was passed in slot `$2` and bails if that's the case.

Quotes can be used if you need an argument with spaces in it (e.g. `my_command "roll tide"`).

Code

function my_command () {
    if [ "$1" ]
    then
        if [ "$2" ]
        then
            echo "You passed too many arguments"
        else
            echo "Got: $1 - Do Stuff Here"
        fi
    else
        echo "You need to pass an argument"
    fi
}