如何使用printf显示计算结果?

如何使用printf显示计算结果?

我的程序是

#!/bin/sh
printf 'Please enter salary amount: '
read salary
TAX="echo $salary * 0.15 | bc"
NET="echo $salary + $TAX | bc"

printf "Net Salary= %.2f" $NET
printf "\n"

但无论我尝试什么,我都无法得到我期望的输出。现在我正在

$ . 3_net_salary.sh 
Please enter salary amount: 300
-bash: printf: echo: invalid number
-bash: printf: +: invalid number
-bash: printf: echo: invalid number
-bash: printf: 1_simple.awk: invalid number
-bash: printf: 1_simple_awk.sh: invalid number
-bash: printf: 2_simple_awk.sh: invalid number
-bash: printf: 2_simple_before.awk: invalid number
-bash: printf: 3_net_salary.sh: invalid number
-bash: printf: 4_purchase_amounts.sh: invalid number
-bash: printf: alert_spec.rb: invalid number
-bash: printf: awk_passwd.sh: invalid number
-bash: printf: numbers.txt: invalid number
-bash: printf: sed_to_change_should_syntax_to_expect-to: invalid number
-bash: printf: should_to_expect: invalid number
-bash: printf: t1_spec.rb: invalid number
-bash: printf: test001.txt: invalid number
-bash: printf: test_1_spec.rb: invalid number
-bash: printf: test_2_spec.rb: invalid number
-bash: printf: |: invalid number
-bash: printf: bc: invalid number
-bash: printf: |: invalid number
-bash: printf: bc: invalid number
Net Salary= 0.00Net Salary= 300.00Net Salary= 0.00Net Salary= 0.00Net Salary= 300.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.15Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00Net Salary= 0.00

答案1

你没有做你认为你正在做的事情。这个命令:

TAX="echo $salary * 0.15 | bc"

不运行任何东西,没有计算。这将一个字符串分配给变量$TAX。然后,因为您在将变量传递给 时没有引用该变量printf,所以*将扩展到当前目录中的所有内容。为了显示:

$ ls
file1  file2
foo="echo 12 * 4 | bc"
$ echo $foo
echo 12 file1 file2 4 | bc

正如您在上面看到的,*扩展为目录的内容并且没有进行任何计算。为了将命令的结果分配给变量,您应该使用var=$(command),而不是引号。

因此,脚本的工作版本将是:

#!/bin/sh
printf 'Please enter salary amount: '
read salary
TAX=$(printf '%s * %s\n' "$salary" "0.15" | bc)
NET=$(printf '%s + %s\n' "$salary" "$TAX" | bc)

printf "Net Salary= %.2f\n" $NET

在调试某些东西时,您应该始终考虑打印变量以了解它们包含的内容。

相关内容