-4

which commands should I use? should I use double parentheses? and if I use 40 + 30 as the two numbers what should be my output? please I'm just starting and I need help.

4
  • 4
    Is this homework for school?
    – sudodus
    Aug 31, 2021 at 8:17
  • Do it one step at a time: write an executable bash script called add that does nothing. Test. Add reading of one argument, and display it. Test. Add a 2nd argument. Test. Add addition. Test (add 40 30, add 0 0, etc). Remove the input printing. Test. … Aug 31, 2021 at 8:37
  • 4
    Don't read solutions to homework questions. You won't learn. Do read other solutions, though. Reading is the best was to learn to write. This question is of the form "write this script for me". Have a go first, ask a specific question, such as "How do I read command line arguments?". You will then get a specific answer, that can be of use to you in future programs. That you can learn from. Aug 31, 2021 at 8:40
  • @sudodus thank you for replying me. Aug 31, 2021 at 9:53

2 Answers 2

2

You mentionned bash, so you can use arithmetic evaluation (see man bash and search for ARITHMETIC EVALUATION).

Example script:

#!/bin/bash

a=$1
b=$2

if (( a > b )); then
    printf '%d\n' "$a"
else
    printf '%d\n' "$b"
fi

Don't forget to validate your input ! Example:

if [[ ! "$1" =~ ^[[:digit:]]+$ ]] ||
   [[ ! "$2" =~ ^[[:digit:]]+$ ]]
then
    echo 'One of the arguments is not a number' >&2
    exit 1
fi
0
echo $(($1 > $2 ? $1 : $2))

But you may want to add some error checking there. For example:

  • Is the number of arguments ($#) correct?
  • Are the arguments well-formed integers, such as ?(-)+([0-9])?

Not the answer you're looking for? Browse other questions tagged .