Check if string equals asterisk in Bash scripting?

6,156

Solution 1

You need to escape or quote the asterisk in the command line:

./calculator.sh 2 \* 2
./calculator.sh 2 '*' 2

and enclose the $2 in double quotes:

if [ "$2" == "*" ]

Solution 2

The problem isn't that the if statement isn't working, it is that the asterisk on the command line is being globbed.

So if your script was called mycalc and run from the command line you do

mycalc 2 * 3

The * will get globbed, and converted to all the names of the files in the current folder.

To avoid expansion, you would need to do

mycalc 2 \* 3

The \ escapes the asterisk and passes it through without changing it.

You might want to consider x for the multiplication operation to avoid this.

Share:
6,156

Related videos on Youtube

jmasterx
Author by

jmasterx

Updated on September 18, 2022

Comments

  • jmasterx
    jmasterx over 1 year

    I'm making a bash script to do basic arthmetic and when I do:

    if [ $2 == "*" ]
    

    it does not work.

    How can I check for asterisk?

    • JdeBP
      JdeBP over 12 years
      Unix Philosophy 102: Let the shell do what the shell does best, and use bc or dc if you want a calculator.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams over 12 years
    Oh good. For a moment I thought I'd need to beat someone over the head with the BASH FAQ.
  • pabouk - Ukraine stay strong
    pabouk - Ukraine stay strong over 10 years
    Unfortunately you do not say how to use the ASCII value for the condition checking.