bash 脚本中的 printf 命令返回“无效数字”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12845997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:31:48  来源:igfitidea点击:

printf command inside a script returns "invalid number"

bashprintf

提问by Ferdinando Randisi

I can't get printfto print a variable with the %e descriptor in a bash script. It would just say

我无法printf在 bash 脚本中使用 %e 描述符打印变量。它只会说

#!/bin/bash
a=14.9
printf %e 14.9;

I know this is likely a very easy question, but I'm fairly new to bash and always used echo. Plus I couldn't find an answer anywhere.

我知道这可能是一个非常简单的问题,但我对 bash 还很陌生并且总是使用echo. 另外,我在任何地方都找不到答案。



when run i get

跑步时我得到

$ ./test.text
./test.text: line 3: printf: 14.9: invalid number
0,000000

therefore my problem is the locale variable LC_NUMERIC: it is set so that i use commas as decimal separators. Indeed, it is set to an european localization:

因此我的问题是语言环境变量 LC_NUMERIC:它的设置使我使用逗号作为小数点分隔符。事实上,它被设置为欧洲本地化:

$ locale | grep NUM
LC_NUMERIC="it_IT.UTF-8"

I thought I set it to en_US.UTF-8, but evidently I didn't. Now the problem switches to find how to set my locale variable. Simply using

我以为我将它设置为 en_US.UTF-8,但显然我没有。现在问题切换到查找如何设置我的语言环境变量。简单地使用

$ LC_NUMERIC="en_US.UTF-8"

won't work.

不会工作。

采纳答案by Keith Thompson

This:

这个:

LC_NUMERIC="en_US.UTF-8" printf %e 14.9

sets $LC_NUMERIConly for the duration of that one command.

$LC_NUMERIC仅在该命令的持续时间内设置。

This:

这个:

export LC_NUMERIC="en_US.UTF-8"

sets $LC_NUMERIConly for the duration of the current shell process.

设置$LC_NUMERIC仅在当前外壳进程的持续时间。

If you add

如果添加

export LC_NUMERIC="en_US.UTF-8"

to your $HOME/.bashrcor $HOME/.bash_profile, it will set $LC_NUMERICfor all bash shells you launch.

到您的$HOME/.bashrcor $HOME/.bash_profile,它将$LC_NUMERIC为您启动的所有 bash shell设置。

Look for existing code that sets $LC_NUMERICin your .bashrcor other shell startup files.

查找$LC_NUMERIC在您的.bashrc或其他 shell 启动文件中设置的现有代码。

回答by Janito Vaqueiro Ferreira Filho

You could have a locale problem, and it wasn't expecting a period. Try:

您可能遇到了语言环境问题,并且没有预料到一个时期。尝试:

LC_NUMERIC="en_US.UTF-8" printf %e 14.9

回答by pedz

I bumped into this error and found this page. In my case, it was 100% pilot error.

我遇到了这个错误并找到了这个页面。就我而言,这是 100% 的飞行员错误。

month=2
printf "%02d" month

it should be

它应该是

printf "%02d" "${month}"

or more simply

或者更简单

printf "%02d" $month