1

I have started learning Unix shell scripting using korn shell. Please enlighten me finding the mistake I am doing while writing a ksh code for below a problem as stated below :

My script takes 2 arguments. I have to sum the arguments if they are numbers, else print them as they are. My code is as below:

#!/usr/bin/ksh

arg1=$1
arg2=$2

if echo $arg1 | grep  '^[0-9]+$' && echo $arg2 | grep '^[0-9]+$'
then
        echo ${expr $arg1 + $arg2}
else
    echo $arg1 and $arg2
fi

I have tried this a number of times to get the right output but all in vain. It always executes the else condition. If I run the script :

sh var_regex_match.sh 40 50

the output I get is :

40 and 50

Please pardon me for any mistake in case I made while posting my question. Thanks much for helping!

1
  • Thanks for sharing your attempts. A good friend to help you debug your scripts is shellcheck.net. – Quasímodo Jul 22 '20 at 17:46
1
  1. Your grep is not set to silent grep. If there were a match, it would be outputed, and you don't want that. So add -q option to suppress grep output on a match.
  2. + is part of extended regular expressions (ERE). To activate them, you need -E flag to grep. Otherwise + is treated as a literal character, and that is why 40 and 50 do not match in your original attempt.
  3. The syntax of expr is wrong.

Correcting those points, the script would become:

#!/usr/bin/ksh
arg1=$1
arg2=$2

if echo "$arg1" | grep -Eq '^[0-9]+$' && echo "$arg2" | grep -Eq '^[0-9]+$'
then
    expr "$arg1" + "$arg2"
else
    echo "$arg1 and $arg2"
fi

However, that takes many roundabouts and expr is deprecated. A more direct approach is

#!/usr/bin/ksh
arg1=$1
arg2=$2

case "$arg1$arg2" in
    *[!0-9]*) echo "$arg1 and $arg2";;
    *) echo "$((arg1+arg2))";;
esac

The case verifies if $arg1 and $arg2 concatenated contain a non-digit. If yes, they are echoed inaltered. Else, their sum is computed.

1
  • 1
    That answers aptly to my question. Thanks a lot ! – Ritesh Jul 22 '20 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.