Blog

03/06/2019

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.

[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

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

20/08/2019

Start your Bitcoin Exchange with our Software

Start your Bitcoin Exchange with our Software Setup your white label bitcoin exchange right away. Or create your own cryptocurrency using...
14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....