Spencer Bharath Spencer Bharath - 3 months ago 9
Bash Question

Pass arguments from command Line and from function inside shell script

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 accepts 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

Answer

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