*避免扩大在bash内置功能使 [英] Avoid expansion of * in bash builtin function let

查看:161
本文介绍了*避免扩大在bash内置功能使的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本的一个问题。我必须使用运算符*为多样信息。取而代之的是脚本错误我有扩张和使用作为运营商的脚本本身的名称。我试着用单引号,但它不工作:(这里的code

 #!/斌/ bash的-x#bash脚本,计算算术前pression
#NO preCEDENCE对于运营商
#符:+ - *如果[$#-lt3]
然后
    回声用法:./calcola.scr< NUM>< OP>< NUM> ...
    1号出口
科幻结果= 0
OP = +
J = 0因为我在$ @

    如果[$ J-eq0]
    然后
        # 第一次尝试
        #result = $(($结果$ $运I))        #第二次尝试
        让的结果$ OP = $ I        J = 1
    其他
        OP = $ I
        J = 0
    科幻
DONE回声结果是$结果退出0


解决方案

如果OP是*,它将由shell脚本,甚至认为它之前扩大。你需要选择别的东西为你的乘法运算符,如x,或强制用户通过将其在单引号或$ P $用反斜杠pceeding它来逃避它。

如果行使的条件允许的话,也许你应该尝试使用读来获得从标准输入前pression,而不是通过命令行让他们的。

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

解决方案

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.

这篇关于*避免扩大在bash内置功能使的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆