njk2015
njk2015

Reputation: 543

Checking script command-line arguments from inside a function

I have the following very simple script:

#!/bin/bash

checkCmdLineArgs() {
    echo -e "num input args $#"
    if (( $# == 0 )); then
        echo "$0 usage: install_dir home_dir"
        exit 255
    fi
}

checkCmdLineArgs

It does not work. If I run it like so:

./test.sh foo bar

It outputs:

num input args 0
./test.sh usage: install_dir home_dir

Any idea why it's failing?

Upvotes: 2

Views: 43

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

Inside a function, $#, $@, and $1 and onward refer to the function's argument list, not the script's. ($0 is an exception, and will still refer to the name passed in the first argv position for the script itself; note that while this is generally the script's name, this isn't firmly guaranteed to be true).

Pass your script's arguments through to the function:

checkCmdLineArgs "$@"

Upvotes: 5

Related Questions