1

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 $#
  • 1
    Is the function defiend inside the script? If so, you can store the argumants to a global array. – choroba Jun 24 '14 at 8:59
3

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
  • Could not up the answer due to lack of points. – Dobz Jun 24 '14 at 11:43
  • In the end I used a case statement. Passing in $#. With this doing the 'if' outside of the function, I was able to pass through, the 3 Args I needed from the Script to the Function.. function_name $2 $3 $4. – Dobz Jun 24 '14 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.