user3438676
user3438676

Reputation: 25

I have a script and I want it to tell me how many paramters it has

I need it to tell me how many parameters i have in the program but it's not working the way I want

if [ "$#" -ne 1 ]; 
then
  echo "Illegal number of parameters is"
  me=`basename $0`
  echo "File Name: $0"
  echo "First Parameter : $1"
fi

Upvotes: 0

Views: 70

Answers (2)

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25865

$# contain all you want whether passed argument to script or number of positional parameters passed to the function.

  #!/bin/bash

    myfunc(){

      echo "The number of positional parameter : $#"
      echo "All parameters or arguments passed to the function: '$@'"
      echo
    }


    printf "No of parameters passed:$#\n" 

    myfunc test123
    myfunc 1 2 3 4 5
    myfunc "this" "is" "a" "test"

Like

$ ./sample.sh 1 2 3 4 5
No of parametere passed:5
The number of positional parameter : 1
All parameters or arguments passed to the function: 'test123'

The number of positional parameter : 5
All parameters or arguments passed to the function: '1 2 3 4 5'

The number of positional parameter : 4
All parameters or arguments passed to the function: 'this is a test'

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77085

When you echo the $# variable, it gives you the number of parameters passed to the script

Content of script.sh

#!/bin/bash

echo "Number of parameters passed are $#"

$ chmod u+x script.sh
$ ./script.sh apple 1 2 ball 3
Number of parameters passed are 4

Upvotes: 2

Related Questions