Avoid expansion of * in bash builtin function let

扶醉桌前 提交于 2019-12-05 12:05:49

If "op" is "*", it will be expanded by the shell before your script even sees it. You need to choose something else for your multiplication operator, like "x", or force your users to escape it by putting it in single quotes or preceeding it with a backslash.

If the terms of the exercise allow it, maybe you should try using "read" to get the expression from standard input instead of getting them from the command line.

If you don't need "* expansion" (referred as "globbing" in general) at all for your script, just start it with "-f"; you can also change it during run time:

mat@owiowi:/tmp/test$ echo *
A B
mat@owiowi:/tmp/test$ set -f
mat@owiowi:/tmp/test$ echo *
*
mat@owiowi:/tmp/test$ set +f
mat@owiowi:/tmp/test$ echo *
A B
Jason Day

It works, you're just not escaping the * correctly. Try using the backslash:

$ ./calcola.scr 2 \* 3
+ '[' 3 -lt 3 ']'
+ result=0
+ op=+
+ j=0
+ for i in '"$@"'
+ '[' 0 -eq 0 ']'
+ let result+=2
+ j=1
+ for i in '"$@"'
+ '[' 1 -eq 0 ']'
+ op='*'
+ j=0
+ for i in '"$@"'
+ '[' 0 -eq 0 ']'
+ let 'result*=3'
+ j=1
+ echo 'Result is 6'
Result is 6
+ exit 0
$

Although, as Paul Tomblin mentioned, it would probably be better to use x as the multiplication operator instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!