Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for the existence of a second argument [duplicate]

Tags:

bash

I need to update this bash function I use for doing things with git:

push() {
  a=$1
  if [ $# -eq 0 ]
    then
      a=$(timestamp)
  fi
  # ... do stuff
}

but I don't know how this line works

 if [ $# -eq 0 ]

I need to check for a first argument and then I need to check for a second argument.

So there will be 2 if statements.

How can I update this and how does this line work

 if [ $# -eq 0 ]
like image 819
cade galt Avatar asked Dec 06 '15 13:12

cade galt


People also ask

Which function is used to check whether first argument is the instance of second argument?

The conditional statement there checks the value of that variable using -eq and it's checking if the value is zero (as in no arguments were passed).

How do you determine the number of arguments passed to the script?

You can get the number of arguments from the special parameter $# . Value of 0 means "no arguments". $# is read-only. When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.


2 Answers

The $# part is a variable that contains the number of arguments passed to the script.

The conditional statement there checks the value of that variable using -eq and it's checking if the value is zero (as in no arguments were passed).

In order to check for two arguments, you can change (or add) that line to read like this:

 if [ $# -eq 2 ]
like image 129
Lix Avatar answered Jan 04 '23 06:01

Lix


You could create a small script to look into how $# changes when you call the function with different numbers of arguments. For instance:

[Contents of "push.sh":]

push() {
    echo $#
}

echo "First call, no arguments:"
push
echo "Second call, one argument:"
push "First argument"
echo "Third call, two arguments:"
push "First argument" "And another one"

If you put this in a script and run it, you'll see something like:

-> % ./push.sh
First call, no arguments:
0
Second call, one argument:
1
Third call, two arguments:
2

This tells you that the value of $# contains the number of arguments given to the function.

The if [ $# -eq 0 ] part you can add to the script, and change the 0 to some other numbers to see what happens. Also, an internet search for "bash if" will reveal the meaning of the -eq part, and show that you could also use -lt or -gt, for instance, testing whether a number is less than or greater than another.

In the end, you'll likely want to use something like the following:

a=$1
b=$2

if [ $# -lt 1 ]
then
   a=$(timestamp)
fi

if [ $# -lt 2 ]
then
    b=$(second thing)
fi
like image 22
joranvar Avatar answered Jan 04 '23 04:01

joranvar