Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bash - printf command inside a script returns "invalid number"

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

#!/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.


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:

$ 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

$ LC_NUMERIC="en_US.UTF-8"

won't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This:

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

sets $LC_NUMERIC only for the duration of that one command.

This:

export LC_NUMERIC="en_US.UTF-8"

sets $LC_NUMERIC only for the duration of the current shell process.

If you add

export LC_NUMERIC="en_US.UTF-8"

to your $HOME/.bashrc or $HOME/.bash_profile, it will set $LC_NUMERIC for all bash shells you launch.

Look for existing code that sets $LC_NUMERIC in your .bashrc or other shell startup files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...