I’m writing a simple calculator in BASH. Its aim is to loop through the arguments given, check if they’re correct, do the power function and pass the rest to the expr to do the calculation. Everything except multiplication works.
When I do something like
my_script.sh 2 \* 2
I get syntax error from expr. Checking with bash -x lets me know that
expr 2 '\*' 2
The * is in apostrophes. I don’t know how to get rid of it so the expr can parse it properly.
if [ $# -le 0 ]
then
usage
exit 1
fi
ARGS=("${@}")
while [ $# -gt 0 ]
do
if [ $OP -eq 0 ]
then
if [[ $1 =~ ^[-]{0,1}[0-9]+$ ]]
then
ELEMS[$J]=$1
shift
let OP=1
let J=$J+1
else
echo $1' is not a number'
usage
exit 3
fi
else
if [[ $1 =~ ^[-+/\^\*]{1}$ ]]
then
if [[ $1 =~ ^[\^]{1}$ ]]
then
if ! [[ $2 =~ ^[0-9]+$ ]]
then
echo 'Bad power exponent'
usage
exit 3
fi
let BASE=${ELEMS[$J-1]}
let EX=$2
pow $BASE $EX
let ELEMS[$J-1]=$RES
shift 2
else
if [[ $1 =~ [\*]{1} ]]
then
ELEMS[$J]=\\*
else
ELEMS[$J]=$1
fi
let J=$J+1
shift
let OP=0
fi
else
echo $1' is not an operator'
if [[ $1 =~ ^[0-9]+$ ]]
then
let TMP=${ELEMS[$J-1]}
echo "Are you missing an operator beetwen $TMP and $1?"
fi
usage
exit 3
fi
fi
done
if [ $OP -eq 0 ]
then
echo 'Missing argument after last operator'
usage
exit 3
fi
echo "Calculation: ${ARGS[*]}"
echo -n 'Result: '
expr ${ELEMS[*]}
Change
ELEMS[$J]=\\*toELEMS[$J]="*"(orELEMS[$J]=\*) and use:The key is to use
@instead of*in the array dereference, which allows you to use double quotes. This is equivalent toexpr "2" "*" "2", instead ofexpr "2 * 2"which you get when usingexpr "${ELEMS[*]}"