2

I want know weather it is possible to pass arguments from command line and from the function inside a shell script

I know its is possible to pass a argument from command line to shell script using

$1 $2 ..

But my problem is my shell script needs to accept arguments from the command line as well as the function inside the shell script .

find my shell script below

#!/bin/bash

extractZipFiles(){
  sudo unzip  "$4" -d "$5"
  if [ "$?" -eq 0 ]
  then
    echo "==>> Files extracted"
    return 0
  else
    echo "==>> Files extraction failed"
    echo "$?"
  fi
}

coreExtraction(){
extractZipFiles some/location some/other/location
}

coreExtraction

echo "====> $1"
echo "====> $2"
echo "====> $3"
echo "====> $4"
echo "====> $5"

I execute my shell script by passing

sudo sh test.sh firstargument secondargument thirdargument 
Amol Katdare
  • 6,740
  • 2
  • 33
  • 36
Spencer Bharath
  • 507
  • 2
  • 7
  • 21

2 Answers2

3

You can forward the original arguments with:

...
coreExtraction () {
    extractZipFiles "$@" some/location some/other/location
}
coreExtraction "$@"
...

To access the original script arguments from inside the function, you have to save them before you call the function, for instance, in an array:

args=("$@")
some_function some_other_args

Inside some_function, the script args will be in ${args[0]}, ${args[1]}, and so on. Their number will be ${#a[@]}.

Matei David
  • 2,322
  • 3
  • 23
  • 36
1

Just pass the arguments from the command line invocation to the function

coreExtraction "$1" "$2" "$3"
# or
coreExtraction "$@"

and add the other arguments to them

extractZipFiles "$@" some/location some/other/location
choroba
  • 231,213
  • 25
  • 204
  • 289