Ubuntu – Echo script arguments from function

14.04bashscripts

I need to get script arguments within function with arguments.

./myscript 1 2 3

function_name () {
   if [ $1 == 3 ]; then
        # I need the $1 in the following echo to be the script argument, not the function argument
        echo $1 $2 $3
   fi
}

function_name $#

Best Answer

That's quite interesting. The problem is the scope of the function is overriding that of the script. I can't see a simple way around that.

However, you can just pass the variables along as arguments (into the function):

function_name () {
   [[ $# == 3 ]] && echo $1 $2 $3
}

function_name $@

Or you could:

  • Pass $# $@, check $1, and echo $2 $3 $4
  • Pass $# $@, check $1, shift and then echo $1 $2 $3
  • Store $@ as a script-level variable and access it from within the function