9

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).

4

4 に答える 4

7

NAME 変数は次のように置き換えられます。

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

これを使って:

#! /bin/sh
NAME="George W. Bush"
printf "Hello, %s\n" "$NAME"
于 2008-09-03T16:40:09.730 に答える
1

私がman ページを解釈する方法は、渡された文字列を引数と見なすことです。文字列にスペースが含まれている場合、複数の引数を渡していると見なされます。変数を引用符で囲み、シェルに文字列を単一の引数として解釈させることで、ColinYounger は正しいと思います。

別の方法として、printf に変数を展開させることもできます。

printf "Hello, $NAME."

リンクはbash用ですが、shにも同じことが当てはまると確信しています。

于 2008-09-03T16:45:35.300 に答える
1

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"
于 2008-09-03T16:39:41.133 に答える
0

If you want all of those words to be printed out on their own, use print instead of printf

printf takes the formatting specification and applies it to each argument that you pass in. Since you have three arguments {George, W., Bush}, it outputs the string three times using the different arguments.

于 2008-09-03T16:39:02.180 に答える