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.