/斌/ bash中的printf不与其他的语言比C工作 [英] /bin/bash printf does not work with other LANG than C

查看:189
本文介绍了/斌/ bash中的printf不与其他的语言比C工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有/斌/ bash和使用printf的格式化字符串中的脚本,一个非常奇怪的问题。

I have a really weird problem with /bin/bash and a script that uses printf to format a string.

我的脚本看起来像这样

rt=$(printf "%.3f" 13.234324245)

与区别,那我计算数13.23 ...以上。当我使用了/ usr / bin中/ zsh中的伟大工程!即使/ bin / sh的可以做到这一点(但如果东西它不能做的......)
最大的问题是IST /斌/ bash中似乎不明白的printf或确有其他格式化的方式,当我不使用 LANG = C

我的LANG变量设置为 de_AT.UTF-8 ,然后我得到这个错误:

My LANG Variable is set to de_AT.UTF-8 and then i get this Error:

/path/to/script: Zeile 12: printf: 13.234324245: Ungültige Zahl.

所以,简单地说,我的printf给了编号无效...

So it simply says that the number i gave printf is invalid...

我是否需要以不同的方式运行的printf?

Do i need to run printf in a different way?

编辑:这个问题似乎是对数的计算:

edit: The problem seems to be on the computation of the number:

rt=$(printf "%.3f" $(echo "$res2 - $res1"|bc ))

我怎么能告诉BC使用,而不是

推荐答案

您的问题源于对 LC_NUMERIC 设置,解析参数的printf 。

Your problem stems for the LC_NUMERIC setting, which bash follows when parsing arguments to printf.

我觉得这种行为可疑。 ksh93的还根据 LC_NUMERIC 解析数而pdksh程序和破折号想要一个点作为参数的分隔和zsh可以接受一个点或局部格式。 POSIX 不说,因为指定的浮点格式是可选的printf LC_NUMERIC 虽然打印数字时必须得到尊重)。

I find this behavior dubious. Ksh93 also parses numbers according to LC_NUMERIC while pdksh and dash want a dot as the separator in the argument, and zsh accepts either a dot or the local format. POSIX doesn't say, because the floating point format specified are optional in printf (LC_NUMERIC must be respected when printing numbers though).

作为一个用户,我建议从来没有设置 LC_NUMERIC LC_COLLATE 除非是非常特殊的情况下,你确定你希望他们的行为。这意味着没有使用 LANG 并设置特定类别代替;大多数人只需要 LC_CTYPE (字符编码), LC_MESSAGES (消息语言)和 LC_TIME (日期和时间格式)。在脚本中,你可以通过设置 LC_ALL ,或者将其设置(设置一个特定的类别 LANG 只覆盖所有类别覆盖 $ LANG ,而不是用户设置的 $ LC_NUMERIC )。

As a user I recommend never setting LC_NUMERIC and LC_COLLATE except in very specific circumstances where you're sure you want their behavior. This means not using LANG and setting specific categories instead; most people only need LC_CTYPE (character encoding), LC_MESSAGES (language of messages) and LC_TIME (date and time format). In a script, you can override all categories by setting LC_ALL, or a specific category by setting it (setting LANG only overrides $LANG and not a user-set $LC_NUMERIC).

#!/bin/sh
LC_NUMERIC=C LC_COLLATE=C
printf "%.3f" 13.234324245

这篇关于/斌/ bash中的printf不与其他的语言比C工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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