Spencer Bharath Spencer Bharath - 1 year ago 66
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


sudo unzip "$4" -d "$5"
if [ "$?" -eq 0 ]
echo "==>> Files extracted"
return 0
echo "==>> Files extraction failed"
echo "$?"

extractZipFiles some/location some/other/location


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 Source

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:

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