I want to run a script that takes arguments in a currency format. Example:

> ./myscript $55.50
total is $55.50
> ./myscript $3.40
total is $58.90

Now, no matter how hard I try to escape the dollar sign in the argument, I get:

> ./myscript $55.50
total is $5.50
> ./myscript $3.40
total is $5.90

So how do you handle currency amounts in shell scripts anyway? Obviously if I specify the amounts in the script I can escape them correctly: variable='$65' OR variable="\$65'

but how do you do this input read in from stdin or command line arguments?


Just escape the dollar sign at the command line. Bash interprets it befor passing it as argument to the script. That why 5.50 is passed to the script ( variable $5 has no value )

./myscript \$55.50

Another way to escape the argument is to enclose it in single quotes in the same way you would within the script:

./myscript '$55.50'

Variable expansion is performed by the shell before the arguments are passed to the executable. Dollar signs introduce parameter expansion (and command substitution and arithmetic expansion. In this case since there's a digit following the dollar sign, it's being treated as a positional parameter so it's looking for the fifth argument. Since you're at a command prompt in an interactive shell, it's not likely that has any value (you can do set -- to affect this, though).

$ echo $55.50
$ echo \$55.50
$ echo '$55.50'
$ set -- aaa bbb ccc ddd eee fff
$ echo $55.50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.