Bash Function: Find Number Of Arguments Passed

How do I find out number of arguments passed to my bash function called foo() under Unix like operating systems?

Each bash shell function has the following set of shell variables: [a] All function parameters or arguments can be accessed via $1, $2, $3,..., $N.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash
Est. reading time 1 minute
[b] $* or $@ holds all parameters or arguments passed to the function. [c] $# holds the number of positional parameters passed to the function. [d] An array variable called FUNCNAME ontains the names of all shell functions currently in the execution call stack.

Example

Create a shell script as follows:

#!/bin/bash
# Purpose: Demo bash function
# Author: nixCraft
# -----------------------------
 
## Define a function called foo()
foo(){
  echo "Function name:  ${FUNCNAME}"
  echo "The number of positional parameter : $#"
  echo "All parameters or arguments passed to the function: '$@'"
  echo
}
 
## Call or invoke the function ##
## Pass the parameters or arguments  ##
foo nixCraft
foo 1 2 3 4 5
foo "this" "is" "a" "test"

Run it as follows:
$ chmod +x script.name.here
$ ./script.name.here

Sample outputs:

Fig.01: Bash function displaying number of arguments passed to foo()

See also

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 3 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • Z. May 8, 2013 @ 1:14

    Try using the special variable ${#}.

    function foo {
    echo “N. of Args: ${#}”
    }

    $ foo a b c
    3

  • Vipul Patil Jun 1, 2021 @ 10:48

    Hi,

    Using ${#} will give the number of arguments but let’s say someone wants to get the name of arguments and value of argument. How one can do that?

    • 🐧 Vivek Gite Jun 1, 2021 @ 17:48

      Are you passing named arg? Like

      ./script -f foo -d bar?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum