2

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?

2
  • 2
    BTW, don't use echo -e -- default builds of bash break the POSIX spec for echo by having it do anything other than print -e on output, but a compliant implementation can be enabled at compile-time or runtime; and other, more-compliant shells will behave contrary to your expectations. (This is unlike most bashisms, which extend the spec rather than breaking it, but echo is explicitly disallowed from accepting any options other than -n). Commented Sep 1, 2017 at 16:20
  • 1
    See pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html, particularly including the APPLICATION USAGE and RATIONALE sections. Commented Sep 1, 2017 at 16:20

1 Answer 1

5

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 "$@"
Sign up to request clarification or add additional context in comments.

3 Comments

Also, there is no $0. It starts at "$1" no?
@pedromss, $0 is the name used for the script itself. Well, sorta/sometimes -- the caller can provide any name in that argv position they want, but that's what it is by convention.
You sir are a genius! Thanks for that. Will mark this as the answer when the timeout has lapsed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.