mercredi 25 octobre 2017

Making a script to take input from a user and use error checking to test if two arguments were entered: Linux

My Linux class just started to begin scripting and I am having trouble with one of my questions. We need to make a script that takes two numbers as arguments and output the sum using bc, we also need to echeck if the user has entered in two arguments.

This is my first script. To get the script to execute you need to do chmod +x filename

This is what I have so far:

#!/bin/bash
read -p "Enter in a numeric value: " num1
read -p "Enter in a second numeric value: " num2
if [ $# -ne 2 ] ; then   
echo "Enter in two numeric arguments"
else
echo "The sum of the entered values are: "
echo "$num1 + $num2"|bc
fi

I keep running into an error. When I enter in two values it displays "Enter in two numeric arguments". It shouldn't do that because if I enter in two values, the if statement will evaluate to false and go to the else statement. Is my logic wrong or am I approaching this the wrong way?

Aucun commentaire:

Enregistrer un commentaire