daverocks
daverocks

Reputation: 2353

How to run a function with parameters with in a bash script

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

Upvotes: 0

Views: 132

Answers (2)

William Pursell
William Pursell

Reputation: 212198

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

Upvotes: 1

cdarke
cdarke

Reputation: 44344

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).

Upvotes: 1

Related Questions