How to access command line arguments of the caller inside a function?

If you want to have your arguments C style (array of arguments + number of arguments) you can use $@ and $#.

$# gives you the number of arguments.
$@ gives you all arguments. You can turn this into an array by args=("$@").

So for example:

args=("$@")
echo $# arguments passed
echo ${args[0]} ${args[1]} ${args[2]}

Note that here ${args[0]} actually is the 1st argument and not the name of your script.


My reading of the Bash Reference Manual says this stuff is captured in BASH_ARGV, although it talks about "the stack" a lot.

#!/bin/bash

shopt -s extdebug

function argv {
  for a in ${BASH_ARGV[*]} ; do
    echo -n "$a "
  done
  echo
}

function f {
  echo f $1 $2 $3
  echo -n f ; argv
}

function g {
  echo g $1 $2 $3
  echo -n g; argv
  f
}

f boo bar baz
g goo gar gaz

Save in f.sh

$ ./f.sh arg0 arg1 arg2
f boo bar baz
fbaz bar boo arg2 arg1 arg0
g goo gar gaz
ggaz gar goo arg2 arg1 arg0
f
fgaz gar goo arg2 arg1 arg0

#!/usr/bin/env bash

echo name of script is $0
echo first argument is $1
echo second argument is $2
echo seventeenth argument is $17
echo number of arguments is $#

Edit: please see my comment on question