TransWikia.com

Conditional regex pattern matching in a korn shell script

Unix & Linux Asked by Ritesh on November 28, 2021

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!

One Answer

  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.

Answered by Quasímodo on November 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP