Reputation: 305
I read this page What are the special dollar sign shell variables? but I still don't get what $#
does.
I have an example from a lecture slide:
#!/bin/sh
echo Total no. of inputs: $#
echo first: $1
echo second: $2
I assume $# takes in all inputs as the argument, and we should expect two inputs. Is that what it's doing?
Upvotes: 0
Views: 214
Reputation: 943
$#
is a special built-in variable that holds the number of arguments passed to the script.
Using the suggested code for example:
#!/bin/sh
echo Total no. of *arguments*: $#
echo first: $1
echo second: $2
If this script is saved to a file, say, printArgCnt.sh, and the executable permissions of printArgCnt.sh are set, then we can expect the following results using $#:
>> ./printArgCnt.sh A B C
Total no. of *arguments*: 3
first: A
second: B
>> ./printArgCnt.sh C B A
Total no. of *arguments*: 3 (<-- still three...argument count is still 3)
first: C
second: B
Upvotes: 3
Reputation: 2160
as your script says: Its total number of command line arguments you are passing to your script.
if you have a script name as: kl.sh
execute it as
./kl.sh hj jl lk
or even bash kl.sh hj jl lk
and in script you are doing
echo $#
It will print 3
where
$1 is hj
$2 is jl
$3 is lk
This tutorial will surely help you
Upvotes: 4