Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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"
}

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

function GetTime()
{
   echo "Get Time function"
   if [ "$#" -ne 1 ]; then
       echo "Illegal number of parameters"
   else
       test1
   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

share|improve this question
5  
Have you missed posting some of your script? How is GetTime() even being called? – GreenAsJade Nov 17 '14 at 15:03
1  
Since when are bash functions defined using a function keyword? – Géza Török Nov 17 '14 at 16:16

1 Answer 1

up vote 3 down vote accepted

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

share|improve this answer
    
But GetTime() isn't getting called anywhere. – anubhava Nov 17 '14 at 15:07
    
@anubhava Op might have missed it. I dont think the output is obtainable without a call to GetTime() – nu11p01n73R Nov 17 '14 at 15:16
    
Thank a lot for the clarification ! – SnP Nov 17 '14 at 15:57
    
@SnP You are welcome :) – nu11p01n73R Nov 17 '14 at 15:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.