Getting number of argument passed to a shell script

Hi Experts,

I have been trying to work on a simple shell script that will just add the two argument passed to it. Here is what i tried :

#!/bin/bash
welcome(){
echo "Welcome to this Progg. which will accept two parameter"
}

main_logic(){
 arg=$#
 echo "Number of argument passed is $arg"
 first_arg=$1
 second_arg=$2
 echo "First argument is $first_arg"
 echo "Second argument is $second_arg"
}

welcome
main_logic

Below is the output which isn't correct :-

Welcome to this Progg. which will accept two parameter
Number of argument passed is 0
First argument is 
Second argument is 

Any idea what am I doing wrong?

you need to give the parameters of the script to the call of the function:

main_logic ${@}

And you must put double quotes around it.

main_logic "$@"

Yes, and as you have already received the solution i wil concentrate on explaining the reason:

When you invoke a process with some arguments these arguments become part of the "process environment". Inside a script you can then use special variables ("$@", "$*", "$1", "$2", ...) to pull these arguments out of the environment or get ("$#") the number of parameters passed.

But every time you invoke a shell function inside a script this function gets its own environment of sorts and all the special variables "$1", "$2", etc. and "$#" describe what is passed as argument to the function instead of what is passed to the main script. Look at the following sample script:

#! /bin/bash

subfunc()
{
    echo "inside subfunc"
    echo "Number of arguments passed: $#"
    echo "argument 1: $1"
    echo "argument 2: $2"
    echo "argument 3: $3"
}

# main part
echo "inside main"
echo "Number of arguments passed: $#"
echo "argument 1: $1"
echo "argument 2: $2"
echo "argument 3: $3"

subfunc a b c
subfunc X Y

And its output will be:

# ./sample.sh foo bar baz blah
inside main
Number of arguments passed: 4
argument 1: foo
argument 2: bar
argument 3: baz
inside subfunc
Number of arguments passed: 3
argument 1: a
argument 2: b
argument 3: c
inside subfunc
Number of arguments passed: 2
argument 1: X
argument 2: Y
argument 3:

I hope this helps.

bakunin

1 Like

Thanks @bakunin, that was useful