Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do $#, $1 and $2 mean? [duplicate]

Tags:

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 :)

like image 355
Fur-gan Avatar asked Apr 25 '16 12:04

Fur-gan


2 Answers

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.

like image 160
donjuedo Avatar answered Oct 13 '22 22:10

donjuedo


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

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

like image 31
Harry Avatar answered Oct 13 '22 21:10

Harry