1

In many scripts in my organisation and even on online tutorials, this is a common if clause I come across :

if [ $# -eq "somethng" -o $# -eq "somethng" ]

what does this $# condition match—some user input by default?
Can this be used on command line directly too??

Timo
  • 6,202
  • 1
  • 26
  • 28
NoobEditor
  • 185
  • 1
  • 2
  • 11
  • In `bash`, see _Special Parameters_ (pp. 8-9) and their expansion (pp. 19...) and finally Conditional Expressions (pp. 28-29) for context. –  Feb 12 '14 at 19:11
  • Things like `$#` are unfortunately difficult to find in the bash documentation. See [this question](http://stackoverflow.com/q/20272085/827263). – Keith Thompson Feb 12 '14 at 19:36
  • @KeithThompson : wow...u just gave me a bang-on ref url!!! :D – NoobEditor Feb 12 '14 at 19:38
  • @KeithThompson I printed the `bash` manual in booklet form using the [livre](https://unix.stackexchange.com/questions/16265/how-to-control-the-page-parameters-margins-brochurisation-of-man-t-postscr/21902#21902) script. A printed version makes a huge difference for me in this context. As is finding an answer like the one you link to which provides the exact terminology for the concepts at hand. –  Feb 12 '14 at 21:39
  • @KeithThompson Also newbie here. But IMHO, $ and # should not appear together in the list on special parameters as conceptually expansion should not be confused with the parameters themselves. Contrary to what I read sometimes $ has nothing to do with variables. As you know it expands a parameter, a variable or enables command substitution or arithmetic expansion. There is an entire section about expansion, including of parameters, with examples. Variable is never defined; "word" and "name" are. Prefixing the params with $ would mean prefixing the shell variables in the next section too... –  Feb 13 '14 at 01:35
  • Actually saying a variable was not defined was wrong as it is defined as a "parameter denoted by a name". But expansion remains unrelated is what I mean here. Anyways, reading this entirely helps but surely it could be more searchable. Maybe there's a way that searching for "$#" could land you in the special params section without having to modify the text. –  Feb 13 '14 at 03:37
  • Also related: [What does $# mean in shell?](https://unix.stackexchange.com/q/122343/80216) – G-Man Says 'Reinstate Monica' Nov 25 '18 at 20:54

1 Answers1

2

$# is number of arguments you passed to bash script, not counting $0, which is program name.

Example:

#!/bin/bash

echo "Number of arguments is: $#"

Then run:

% cuonglm at ~
% ./test.sh a b c d
Number of arguments is: 4
cuonglm
  • 150,973
  • 38
  • 327
  • 406