Hunter Zhao
Hunter Zhao

Reputation: 4659

Why can't get the shell script's parameter count in a function

I'm confused about why can't get the script's parameter count in a function, could anybody help me? thanks in advance:)
test.sh

#!/bin/bash
check(){
    echo $#
    if [ $# -lt 2 ]; then
        echo "Argument missing"
        exit 1
    fi
}
echo $#
check

Run:

./test.sh aa bb

output:

2
0

Upvotes: 1

Views: 62

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

Functions have their own local copies of the argument variables, including $#. They are related to the arguments of the function, and the equivalents at the script level are shadowed. If you want to get the script's argument variables then you will need to either store them somewhere else first or pass them to the function.

check "$@"

Upvotes: 7

Related Questions