尝试添加" $"时出现语法错误在数字

时间:2017-03-15 09:56:24

标签: bash shell

我试图添加" $"在下面计算的数字前面;唯一一个能够添加" $"是限制,因为它与总数等没有任何数学冲突。我如何在成本,提示,总计,平均值中添加美元符号。我尝试添加它像我做的限制,但它给了我一个语法错误。请帮我解决这个问题!

Percent=20
function calc {
  echo -n "What is the total cost in cents?";
  read cents
  guests=5
  Limit='$'$(awk "BEGIN{printf \"%.2f\n\", guests * 10  "); #added successfully
  Cost=$(echo "scale =2; $cents/100" | bc); #need to add $
  Percent=$(echo "scale =2; $Percent / 100" | bc);
  Tip=$(echo "scale =2; $Cost * $Percent" | bc); #need to add $
  Total=$(echo "scale =2; $Cost + $Tip" | bc); #need to add $
  Average=$(echo "scale =2; $Total/guests" | bc); #need to add $
}

我有一个类似的代码已发布,但它并不相同,因为之前的代码并不能帮助我解决" $"我现在有的问题

2 个答案:

答案 0 :(得分:2)

在仍使用变量计算某些内容时,无法将$添加到变量中。它适用于Limit因为Limit未在以下计算中使用。 “手动”执行程序,看看会发生什么:

会发生什么:

Cost='$12.00' # value computed by hand
Tip='$1.00'   # value computed by hand
Total=$(echo 'scale=2; $12.00 + $1.00' | bc); # filled in values of variables

bc不知道如何处理$。在没有$的情况下完成所有计算,然后(在最后)添加$

# ongoing calculations
Cost='$'"$Cost"
Tip='$'"$Tip"
Total='$'"$Total"
Average='$'"$Average"

答案 1 :(得分:1)

简单的答案是,您可以通过引用或转义需要保护的部分来粘贴字符串,在这种情况下是$字符,否则它是shell元字符。

Average=\$$(echo "scale =2; $Total/guests" | bc)  # or
Average='$'$(echo "scale =2; $Total/guests" | bc) # or
Average="$"$(echo "scale =2; $Total/guests" | bc)

你的实际问题似乎是你在Awk中使用guests就好像它是一个Awk变量,但是awk并不知道shell有一个带有这个名字的变量。

更重要的是,在子shell中运行大量echo命令是反模式。您已经在使用Awk - 重构它,因此它可以一次性生成您需要的所有结果。也许是这样的:

Percent=20
calc () {   # notice also the switch to POSIX function definition syntax
  read -p "What is the total cost in cents?" cents
  # Can't use shell variable in Awk script!
  set -- $(awk -v guests=5 -v cents="$cents" -v percent="$Percent" '
    BEGIN{cost=cents/100; tip=cost*percent; total=cost+tip; average=total/guests;
        printf "%.2f $%.2f %.2f $%.2f $%.2f $%.2f\n", guests * 10,
            cost, percent/100, tip, total, average}')
  Limit=$1
  Cost=$2
  Percent=$3
  Tip=$4
  Total=$5
  Average=$6
}

set -- some tokens的功能是将$1设置为some,将$2设置为tokens等,即快速简洁(但可以说是模糊不清)将命令行参数设置为您选择的一组值的方法。

您会注意到我将美元符号计入printf格式字符串。

更基本的是,让一个函数创建大量的变量以便在shell脚本的其他地方使用,这也是一种含糊但却截然不同的难闻气味。你确定这个脚本真的想成为一个shell脚本吗?你真的确定这个特殊的设计是可维护的吗?

相关问题