避免在 bash 内置函数 let 中扩展 *
我的 bash 脚本有问题。 我必须使用运算符 * 来进行乘法。 相反,脚本的扩展和使用脚本本身的名称作为操作符让我感到烦恼。 我尝试使用单引号,但它不起作用:( 这是代码
#!/bin/bash -x
# Bash script that calculates an arithmetic expression
# NO PRECEDENCE FOR OPERATORS
# Operators: + - *
if [ "$#" -lt "3" ]
then
echo "Usage: ./calcola.scr <num> <op> <num> ..."
exit 1
fi
result=0
op=+
j=0
for i in "$@"
do
if [ "$j" -eq "0" ]
then
# first try
#result=$(( $result $op $i ))
# second try
let "result$op=$i"
j=1
else
op=$i
j=0
fi
done
echo "Result is $result"
exit 0
I have a problem with a bash script. I have to use the operator * to multiplicate. Instead the script bugs me with expansion and using as operator the name of the script itself. I tried with single quotes but it doesn't work :( Here's the code
#!/bin/bash -x
# Bash script that calculates an arithmetic expression
# NO PRECEDENCE FOR OPERATORS
# Operators: + - *
if [ "$#" -lt "3" ]
then
echo "Usage: ./calcola.scr <num> <op> <num> ..."
exit 1
fi
result=0
op=+
j=0
for i in "$@"
do
if [ "$j" -eq "0" ]
then
# first try
#result=$(( $result $op $i ))
# second try
let "result$op=$i"
j=1
else
op=$i
j=0
fi
done
echo "Result is $result"
exit 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的脚本根本不需要“*扩展”(通常称为“globbing”),只需以“-f”开头即可; 您还可以在运行时更改它:
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:
如果“op”是“*”,那么在脚本看到它之前,它就会被 shell 扩展。 您需要为乘法运算符选择其他内容,例如“x”,或者强制用户通过将其放在单引号中或在其前面添加反斜杠来转义它。
如果练习的条款允许,也许您应该尝试使用“read”从标准输入获取表达式,而不是从命令行获取它们。
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.
它有效,只是您没有正确转义
*
。 尝试使用反斜杠:虽然,正如 Paul Tomblin 提到的,使用
x
作为乘法运算符可能会更好。It works, you're just not escaping the
*
correctly. Try using the backslash:Although, as Paul Tomblin mentioned, it would probably be better to use
x
as the multiplication operator instead.