Home > other >  Bash takes an input with special character
Bash takes an input with special character

Time:05-21

I am writing a simple calculator script with bash

#! /bin/bash

arg1=$1
arg2=$2
arg3=$3

case $arg2 in

   " ")
    res=$((arg1 arg3))
    ;;
   "-")
    res=$((arg1-arg3))
    ;;
   '*')
    res=$((arg1*arg3))
    ;;
   "/")
    res=$((arg1/arg3))
    ;;
    *)
     echo "Incrorrect format"
    ;;
esac

echo $res

The script call is like

$ bash calc.sh 10 * 2

The only operation that doesn't work correctly is * as the asterisk is a special character. How can I solve this?

The bash calc.sh 10 * 2 part needs to stay the same. How do I change the script, not the input?

CodePudding user response:

Escape the wildcard * using either of the below options:

bash calc.sh 10 \* 2
bash calc.sh 10 '*' 2
bash calc.sh 10 "*" 2

CodePudding user response:

I'd suggest to use read in your script to be more convenient like this

#! /bin/bash

read -p 'Enter first arg: '  arg1
read -p 'Enter operator: '   arg2
read -p 'Enter second arg: ' arg3

case $arg2 in

   " ")
    res=$((arg1 arg3))
    ;;
   "-")
    res=$((arg1-arg3))
    ;;
   '*')
    res=$((arg1*arg3))
    ;;
   "/")
    res=$((arg1/arg3))
    ;;
    *)
     echo "Incrorrect format"
    ;;
esac

echo $res
  •  Tags:  
  • bash
  • Related