Linux Bash-格式化值
我已经用bash编写了一个简单的帐户脚本,但我找不到显示浮点值的标准方法。这是使用awk的最佳解决方案吗?余额也打印出了0.00,我忘了包括什么吗Linux Bash-格式化值,linux,bash,shell,Linux,Bash,Shell,我已经用bash编写了一个简单的帐户脚本,但我找不到显示浮点值的标准方法。这是使用awk的最佳解决方案吗?余额也打印出了0.00,我忘了包括什么吗 #!/bin/bash function printBalance() { echo | awk 'BEGIN { printf "\nCurrent balance: %.2f\n", balance }' sleep 1 } function makeWithdraw() { echo -en "\nWithdraw
#!/bin/bash
function printBalance()
{
echo | awk 'BEGIN { printf "\nCurrent balance: %.2f\n", balance }'
sleep 1
}
function makeWithdraw()
{
echo -en "\nWithdraw an amount: "
read deposit
if [ "$withdraw" -gt "$balance" ]; then
echo -en "\nInsufficient funds"
sleep 1
else
balance=$(( balance - withdraw ))
fi
}
balance=$((RANDOM%100+1))
# code continues...
awk
应该这样做
$ awk 'BEGIN {printf "%.3f\n", 10 / 3}'
3.333
awk
应该这样做
$ awk 'BEGIN {printf "%.3f\n", 10 / 3}'
3.333
现在我看到缺少了什么:
awk
需要给变量余额
:
如果您有$myvar
,您必须:
awk -v awk_internal_var=${myvar} '{printf "%s", awk_internal_var}'
就你而言:
echo | awk -v balance=${balance} 'BEGIN { printf "\nCurrent balance: %.2f\n", balance }'
这就是为什么它要打印
0.00
:因为它没有得到值。现在我看到缺少了什么:awk
需要给变量余额
:
如果您有$myvar
,您必须:
awk -v awk_internal_var=${myvar} '{printf "%s", awk_internal_var}'
就你而言:
echo | awk -v balance=${balance} 'BEGIN { printf "\nCurrent balance: %.2f\n", balance }'
这就是为什么它要打印
0.00
:因为它没有得到值。只需使用bash的内置printf
命令:
$ printf '%.2f\n' 123.456
123.46
对于任何复杂的事情,我也建议使用printf
而不是echo
。在不同的shell中有多个版本的echo
,作为独立的程序。printf的情况也是如此,但其行为更加一致
例如,而不是
echo -en "\nWithdraw an amount: "
您可以使用:
printf '\nWithdraw an amount: '
或者,如果字符串可能包含%
字符:
printf '\n%s: ' 'Withdraw an amount'
只需使用bash的内置
printf
命令:
$ printf '%.2f\n' 123.456
123.46
对于任何复杂的事情,我也建议使用printf
而不是echo
。在不同的shell中有多个版本的echo
,作为独立的程序。printf的情况也是如此,但其行为更加一致
例如,而不是
echo -en "\nWithdraw an amount: "
您可以使用:
printf '\nWithdraw an amount: '
或者,如果字符串可能包含%
字符:
printf '\n%s: ' 'Withdraw an amount'
awk
的printf
与c
的工作原理相同,所以你做这件事的方式很好。唷,我还是习惯于Bash。平衡是一个随机数,我在下面播了种子,你知道为什么它会打印出零吗@Fedorqui你的printBalance
函数中的echo |
的作用是什么?我完全不明白,谢谢@KeithThompsonawk
的printf
与c
的工作原理相同,所以你做的方式很好。唷,我还是习惯Bash。平衡是一个随机数,我在下面播了种子,你知道为什么它会打印出零吗@Fedorqui在您的printBalance
函数中使用echo |
的目的是什么?我完全没听清楚,谢谢@KeithThompsonI,我真的很感谢您的解释。它就像一个符咒!我明白了,我真的很感谢你的解释。它就像一个符咒!现在进行更改!使用单引号和双引号有什么区别吗?我知道在php中双引号被认为是“神奇的”。现在就进行更改!使用单引号和双引号有什么区别吗?我知道在php中,双引号被认为是“魔法”。