0

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?

Community
  • 1
  • 1
user3511965
  • 195
  • 1
  • 3
  • 9
  • Maybe it is not very clear, but in the link it indicates that it `counts` – fedorqui May 07 '14 at 20:36
  • 2
    It's just the number of arguments passed via the command line. – ooga May 07 '14 at 20:37
  • 1
    It doesn't actually *do* anything. It's not a command. It's a special variable that *contains* the count of parameters passed to your script. The value is set by bash when the script it called. Edit: And bash updates its value if/when you do a `shift`. – Mike Holt May 07 '14 at 20:37
  • The top answer in the x-ref'd question is disappointingly casual and really woefully incomplete in its treatment of `$#`, `$@` and `$*`. The last two, in particular, require quite a lot more explanation than they're given, not least because `$*` is the same as `$@`, but `"$*"` is quite different from `"$@"` (in general), and both of these are quite different from the unquoted forms (again, in general). The other answer is a little better, but still incomplete. – Jonathan Leffler May 07 '14 at 21:02

2 Answers2

4

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

PradyJord
  • 2,136
  • 12
  • 19
3

$# 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
RichS
  • 913
  • 4
  • 12
  • I believe I deserve my point back. I answered the question correctly. – RichS May 07 '14 at 20:51
  • 'Total number of inputs' is terminology from the script in the question. It might be better to change 'input' to 'args' or 'arguments'. Inputs tends to refer to files, some of which might be specified by arguments, but 'standard input' is also an input, and the environment can also provide inputs (secretly; it isn't always a good idea to use environment variables). – Jonathan Leffler May 07 '14 at 21:01
  • Ok, fair enough. Edited per request. – RichS May 07 '14 at 21:07