expr: syntax error: unexpected argument ‘Desktop’

Here is my bash script for converting the input temperature from Celsius to Fahrenheit.

#!/bin/bash
echo "Enter temperature in degrees Celsius: "
read celsius
temp=$(expr $celsius * 9 / 5 + 32 )
echo "Temperature in degrees Fahrenheit: $temp"

I got this error message:

expr: syntax error: unexpected argument ‘Desktop’

Do you have any solutions?


Solution 1:

The * symbol is a shell glob (filename generation) character it will expand to a list of the non-hidden files in the current directory - in your case, that appears to include a Desktop item.

To prevent that, you either need to turn off shell globbing, using set -f or set -o noglob:

#!/bin/bash
set -f
echo "Enter temperature in degrees Celsius: "
read celsius
temp=$(expr "$celsius" * 9 / 5 + 32 )
echo "Temperature in degrees Fahrenheit: $temp"

or either quote or escape the * character to make it literal:

#!/bin/bash
echo "Enter temperature in degrees Celsius: "
read celsius
temp=$(expr "$celsius" \* 9 / 5 + 32 )
echo "Temperature in degrees Fahrenheit: $temp"

In either case you should get into the habit of double-quoting shell expansions like $celsius, to prevent shell expansion and word-splitting (especially when they contain arbitrary user input).

Solution 2:

Corrected bash script for converting the input temperature from Celsius to Fahrenheit using the popular bc terminal program instead of expr in line 4:

#!/bin/bash
echo "Enter temperature in degrees Celsius: "
read celsius
temp=`echo "scale=1; $celsius*1.8 + 32" | bc` 
echo "Temperature in degrees Fahrenheit: $temp"

bc for "basic calculator" is an arbitrary precision calculator language. bc is a lot more intuitive and easier to use than working clumsily and fumbling with an expr syntax error. The value of the scale function is the number of digits after the decimal point in the expression.