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 :)
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.
$#
Denotes the number of command line arguments or positional parameters
$1
and $2
denote the first and second command line argument passed, respectively
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With