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 

2 Answers 2

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[@]}.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Thanks @choroba .. I dont want to pass the same arguments from the command line to the function inside the shell script , I need to pass a different argument to the the function inside the shell script ..Is there a way to do it .
Addressed this in my answer.
@SpencerBharath: Pass whatever arguments you need.

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.