避免在bash内置函数中扩展*

gc5*_*gc5 4 bash scripting let expansion

我有一个bash脚本的问题.我必须使用运算符*来进行乘法运算.相反,脚本会让我厌倦扩展,并使用as运算符作为脚本本身的名称.我尝试使用单引号但它不起作用:(这是代码

#!/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
Run Code Online (Sandbox Code Playgroud)

Mat*_*euP 8

如果你的脚本根本不需要"*扩展"(一般称为"globbing"),只需用"-f"启动它; 你也可以在运行时更改它:

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
Run Code Online (Sandbox Code Playgroud)


Pau*_*lin 6

如果"op"是"*",它将在脚本甚至看到它之前由shell扩展.您需要为乘法运算符选择其他内容,例如"x",或者强制用户通过将其放在单引号中或在其前面加上反斜杠来逃避它.

如果练习的条款允许,也许您应该尝试使用"read"从标准输入获取表达式,而不是从命令行获取它们.