shell - multiplicator operation bash issue -


from stdin read string , if it's this:

"numberone * numbertwo"

i have execute multiplicator between numberone , numbertwo.

this code:

read string regex2="^[1-9]+ \*{1,1} [1-9]+$"      if [[ $string =~ $regex2 ]];           val=1          val1=`echo $string|cut -d " " -f 1`          val2=`echo $string|cut -d " " -f 3`           ((val=$val1*$val2))#comment           echo $val     fi 

but 2 errors:

1) on line calculate operation ((val=$val1*$val2)), says syntax error : arithmetic operator invalid

2) , shell , insert input string, example 3 * 2 on shell prints list of files, thought jolly character "*", , reason substuited input string this:

3 \* 2 

but result doesn't change

always, always quote expansions.

echo $string, when $string contains * surrounded whitespace, treats * glob, replacing list of filenames in current directory. filenames not part of legitimate math operation.

use echo "$string" instead, if must use echo @ all; printf '%s\n' "$string" alternative works in corner cases echo fails (and/or behaves in ways unspecified posix).


that said, there's no legitimate reason use cut here @ all; regex split string pieces on own.

regex2='^([1-9][0-9]*) [*] ([1-9][0-9]*)$' read -r string  if [[ $string =~ $regex2 ]];      val=$(( ${bash_rematch[1]} * ${bash_rematch[2]} ))       echo "$val" fi 

...and if couldn't that, better practice use read:

read val1 _ val2 <<<"$string" echo "$(( val1 * val2 ))" 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -