Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Bourne shell printf iterate over a %s argument?

Tags:

shell

unix

What's going on here?

printf.sh:

#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" $NAME

Command line session:

$ ./printf.sh
Hello, George
Hello, W.
Hello, Bush

UPDATE: printf "Hello, %s\n" "$NAME" works. For why I'm not using echo, consider

echo.sh:

#! /bin/sh
FILE="C:\tmp"
echo "Filename: $FILE"

Command-line:

$ ./echo.sh
Filename: C:    mp

The POSIX spec for echo says, "New applications are encouraged to use printf instead of echo" (for this and other reasons).

like image 329
Chris Conway Avatar asked Sep 03 '08 16:09

Chris Conway


2 Answers

Your NAME variable is being substituted like this:

printf "Hello, %s\n" George W. Bush

Use this:

#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" "$NAME"
like image 188
ColinYounger Avatar answered Sep 28 '22 00:09

ColinYounger


is there a specific reason you are using printf or would echo work for you as well?

NAME="George W. Bush"
echo "Hello, "$NAME

results in

Hello, George W. Bush

edit: The reason it is iterating over "George W. Bush" is because the bourne shell is space delimitted. To keep using printf you have to put $NAME in double quotes

printf "Hello, %s\n" "$NAME"
like image 44
Tanj Avatar answered Sep 27 '22 22:09

Tanj