1

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

2
  • 5
    Have you missed posting some of your script? How is GetTime() even being called? Commented Nov 17, 2014 at 15:03
  • 1
    Since when are bash functions defined using a function keyword? Commented Nov 17, 2014 at 16:16

1 Answer 1

3

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

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

2 Comments

But GetTime() isn't getting called anywhere.
@anubhava Op might have missed it. I dont think the output is obtainable without a call to GetTime()

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.