Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf command inside a script returns "invalid number"

Tags:

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.

like image 785
Ferdinando Randisi Avatar asked Oct 11 '12 18:10

Ferdinando Randisi


People also ask

What is ${ 0 * in shell script?

${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh , then ${0} will be exactly that string: path/to/script.sh . The %/* part modifies the value of ${0} . It means: take all characters until / followed by a file name.

Does printf work in bash?

The bash printf command is a tool used for creating formatted output. It is a shell built-in, similar to the printf() function in C/C++, Java, PHP, and other programming languages. The command allows you to print formatted text and variables in standard output.

What is $@ bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

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.

UPDATE:

If the $LC_NUMERIC environment variable is not set, the LC_NUMERIC locale setting can be set from the $LANG or $LC_ALL. Check your environment variable settings as well as the output of the locale command. $LC_ALL overrides $LC_NUMERIC, and $LC_NUMERIC overrides $LANG. man locale and/or man 7 locale for details.

like image 153
Keith Thompson Avatar answered Oct 26 '22 05:10

Keith Thompson


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

LC_NUMERIC="en_US.UTF-8" printf %e 14.9
like image 40
Janito Vaqueiro Ferreira Filho Avatar answered Oct 26 '22 04:10

Janito Vaqueiro Ferreira Filho