Home > Net >  Is the purpose of the %d conversion specifier to verify that the argument consists exclusively of di
Is the purpose of the %d conversion specifier to verify that the argument consists exclusively of di

Time:11-30

printf "This is a number: %d\n" 10
> This is a number: 10

My understanding is that %d means: the argument is an integer. But the argument (10) isn't an integer, it's a string consisting of two characters: '1' and '0'. Is the purpose of %d to check the argument to ensure that the string consists exclusively of digit characters? Even though it's called a "conversion specification" there isn't any converting actually occurring, right?

CodePudding user response:

Shell is not C. You cannot really pass a 32/64-bit integer to shell's printf which only accepts strings.

Bash's printf does report error on invalid inputs so it can be used to validate numbers:

$ printf '%d\n' abc
bash: printf: abc: invalid number
0
$ echo $?
1
$ printf '%d\n' 123abc
bash: printf: 123abc: invalid number
123
$ echo $?
1

But I think it's more useful when you want to print something in specific formats:

$ printf '           
  •  Tags:  
  • bash
  • Related