Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $d do in printf?

I accidentaly wrote:

printf "here: %s $d\n" "${line:0:32}" "${#line}"

and got:

here: /home/gsamaras/Bash/libs/goodLib 
here: 103 

Why?

Of course I meant to say %d, but I don't understand this behavior in the mistake I made. I would probably expect it to print "here: /home/gsamaras/Bash/libs/goodLib $d", like it would do in C... I couldn't find a duplicate or something on that, thus the question.

like image 836
gsamaras Avatar asked Nov 16 '25 16:11

gsamaras


1 Answers

Before the string "here: %s $d\n" is passed to printf, parameter expansions are performed by the shell. In this case $d is expanded to an empty string.

If you used single quotes around the string, or backslash-escaped the $, then you would see $d in the output.

Since you only have one format specifier in your string (%s) and passed two arguments after the format string, you end up with two lines of output:

The format is reused as necessary to consume all of the arguments.

(from man bash in the printf section).

like image 126
Tom Fenech Avatar answered Nov 19 '25 08:11

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!