ogs
ogs

Reputation: 1239

bash script check input argument

Today, I have to check the existence and the number of input arguments. I have the following script:

#!/bin/bash

echo "*** Test ***"
echo
echo $#
echo $*

function test1(){
   echo "test"
}

function GetTime()
{
   echo "Get Time function"
   if [ "$#" -ne 1 ]; then
       echo "Illegal number of parameters"
   else
       test1
   fi
}

if [ "$#" -ne 1 ]; then
    echo "Illegal number of parameters"
else
    test1
    GetTime  
fi

When I enter ./test.sh GetTime I get

*** Test ***

1
GetTime
test
Get Time function
Illegal number of parameters

I do not understand why the behavior is different between the first condition and the one contains within the GetTime() function. Somebody could help me ?

Thank in advance

Upvotes: 1

Views: 3702

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

It is different because $# in first if refer to the number of arguments to the shell script. Where as the $# in second indicates the number of argument to GetTime function

To understand more I have modified the GetTime function as

#!/bin/bash

echo "*** Test ***"
echo
echo $#
echo $*

function test1(){
   echo "test"
}

if [ "$#" -ne 1 ]; then
    echo "Illegal number of parameters"
else
    test1   
fi

function GetTime()
{
   echo "Get Time function"
   echo "$# $@"
   if [ "$#" -ne 1 ]; then
       echo "Illegal number of parameters"
   else
       test1
   fi
}

GetTime 
GetTime 2 

Giving output as

*** Test ***
1
GetTime
test
Get Time function
0 
Illegal number of parameters
Get Time function
1 2
test

Here for the first call GetTime gives

Get Time function
0 
Illegal number of parameters

Where 0 is the number of parameters passed

and Second call as GetTime 2

produced output

Get Time function
1 2
test

Where 1 is the number of parameters passed and 2 is the argument itself

Upvotes: 3

Related Questions