7

My question is about a bash-programme, which is in this big book about programming a raspberry pi (bash, Python, C).

There is a sample programme to show how the if works in bash, but no matter how many times a read through the description of the programme, it just doesn't seem to explain properly what it does (I know it's too much to ask if I want a thorough bash tutorial in a 1000 pages book, and that's why I'm here)

So here is the code:

#!/bin/bash

if test $# -ne 2; then
    echo "You have to pass 2 arguments to the command"
    #argument / parameter, whatever you prefer
    exit 1
else
    echo "Argument 1: $1, argument 2: $2"
fi

I understand, that the -ne 2 means: not equal to 2, so it checks if the $# is equal to 2, but I don't understand what it does (the $#). -> First question

In the else it prints the $1 and $2, but I thought that $variablename would print the value of that variable. How can an integer be a variable? -> second question

And yes, I google'ed and didn't find anything of use (maybe didn't search enough?), which is exactly why I'm here.

I would appreciate any kind of help, be it a link to read it myself, or a short explanation. Thanks in advance :)

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Fur-gan
  • 107
  • 1
  • 3
  • 10
  • This is also something readily available in man pages and static web pages you can search for. Not sure this was ever worthy of a StackOverflow response. – SaintHax Apr 25 '16 at 13:53
  • If you're going to be using `bash`, I strongly recommend that you read the manual! In a terminal, `man bash` or [Bash Reference Manual](https://www.gnu.org/software/bash/manual/bash.pdf), in a PDF file. – user3439894 Apr 25 '16 at 14:46

2 Answers2

4

The $# refers to the number of parameters received at run time, not a specific parameter. $1 gets replaced by whatever was in location 1 on the command line when the script was executed.

donjuedo
  • 2,475
  • 18
  • 28
1

$# Denotes the number of command line arguments or positional parameters

$1and $2 denote the first and second command line argument passed, respectively

Harry
  • 1,362
  • 12
  • 19