1

I'm trying to write a script that adds three specified arguments together, and if there are no arguments outputs: "No arguments".

The trouble is that "No arguments" is always output even when there are three arguments.

I am very new to shell script.

Here is my script:

#!/bin/sh
if [[("$#"==0)]]; then 
echo "No arguments specified"
exit 1
fi


sum=0
sum=$(expr $1 + $2 + $3)
echo "$sum"
exit 0
0

2 Answers 2

6

Either change your shebang to #!/bin/bash and use

if (( $# == 0 )); then

or use the POSIX-compatible [:

if [ $# -eq 0 ]; then

Don't forget that [ and [[ are both commands, not syntax, so as with any other command, you need to separate the arguments you pass to the command with spaces.

If you are using bash features, such as [[, you should always use the #!/bin/bash shebang, as otherwise you will run into problems.

As pointed out in the comments below the other answer, it is possibly a better idea to check that you have been passed three arguments:

#!/bin/bash
if (( $# < 3 )); then 
    echo "Insufficient number of arguments specified"
    exit 1
fi

sum=$(( $1 + $2 + $3 ))
echo "$sum"

I have made a couple of other changes to your script, such as not initialising sum to 0 and using the more modern $(( )) to evaluate the sum of the variables.

Sign up to request clarification or add additional context in comments.

Comments

3

I guess what you ask for is:

if [ $# -eq 0 ];

2 Comments

@user3344179 it might also be worth considering using -lt rather than -eq, as this will test for any of the three arguments not being set, rather than only if no arguments have been set.
If a program asks for a specific number of arguments I'd say it's better to look for that number, thus give an error on too many arguments. In both cases (too few or too many args) the user have probably done something wrong and should be notified. That's how I want it atleast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.