0

I trying to run a function outside of my script. Example test.sh:

DAYS=10
IP=1.2.3.4

Main {
   functionName ${DAYS} ${IP}
   }

 functionName() {
   echo $1
   echo "$2"
   }

from command line I'm trying to run the scripts function with different parameters

./test.sh functionName 4 "1.3.4.5"

Having trouble getting it to work so any ideas would be great thanks

1
  • Functions must be defined before called. Commented Jul 4, 2012 at 11:04

2 Answers 2

1

Inside the function, $1 is the argument passed to the function, not the argument passed to the script. Just do:

DAYS=${1-10}    # set DAYS to first argument, defaulting to "10"
IP=${2-1.2.3.4} # set IP to 2nd argument, defaulting to "1.2.3.4"

Main() {
    functionName ${DAYS} ${IP}
}

functionName() {
    echo $1
    echo "$2"
}
Main
Sign up to request clarification or add additional context in comments.

Comments

1

If you source your script, then the functions will be available in your current shell:

. ./test.sh
functionName 4 "1.3.4.5"

Downside is that any code in the sourced script which is not in a function will be run. You can avoid that by (in the sourced script) doing a test like:

if [[ $0 == test.sh ]] 
then 
    Main
fi

which might be why you have a Main? By the way, why are you using global variables? Why not declare them inside Main (using local).

1 Comment

I'm just updating a script that was written by someone else so just following the same flow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.