0

Trying to make a program where it takes two arguments from the command line and adds them together. However if there are not two arguments passed it needs to ask for two arguments.

if [$# = 2]; then
ans=$(($1 + $2))
echo "$1 + $2 = $ans"
else
echo "Pass me two Arguments!"
fi

What is the correct way to check whether the number of arguments is equivalent to a number?

1 Answers1

2

You got it but just forgot some escaping quotes and the spaces before/after the test ([$# = 2]). Fixed:

if [ "$#" = 2 ]; then
ans=$(($1 + $2))
echo "$1 + $2 = $ans"
else
echo "Pass me two Arguments!"
fi

Odd as it may seem, [ is actually the name of an executable just like echo, ls and what have you:

$ which [
/usr/bin/[

This means that if you don't have a space after [, you're trying to start a program called [your_statement. The space is needed to separate the executable from its arguments.

Most *nix systems allow you to use the equivalent test executable rather than [ for a more intuitive syntax: if test "$#" = 2; then ...

By omitting the quotes in the if statement, bash/shell interprets everything following the # as a comment and so does SO's code formatting tool (everything after if [$ is greyed out in your code but not in mine because I added the double quotes in "$#").

Btw. ShellCheck can be very helpful.

jDo
  • 3,962
  • 1
  • 11
  • 30