Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use printf '%s\n' "message"?

if [[ -z "$usr_name" ]]; then
   printf '%s\n' "No input entered"
   exit 1

What is the meaning of '%s\n' and why would you add it instead of just using:

printf "No input entered"
like image 726
Gee_k Avatar asked May 31 '26 21:05

Gee_k


2 Answers

It's a defensive programming technique, hoping to prevent errors in which the format string contains unexpected directives or the number of arguments does not match the format string. Also, putting the string in an argument reduces unnecessary escapes. (Compare printf '20%%\n' and printf '%s\n' '20%') It also makes the format easier to see for the reader, helping prevent the mistake of forgetting the trailing newline.

Bottom line: it's a stylistic decision. There's no functional difference between:

printf '%s\n' 'No input entered'

and

printf 'No input entered\n'
like image 90
William Pursell Avatar answered Jun 03 '26 10:06

William Pursell


printf is used for format and print data. In the case of:

printf '%s\n' "No input entered"

%s represents a string place holder for the space separated string that follows and "\n" represents a line feed.

%s will then be substituted for "No input entered", followed by a line feed.

like image 23
Raman Sailopal Avatar answered Jun 03 '26 11:06

Raman Sailopal



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!