1

I am making a program shell (#!/bin/sh) and the problem is that printf show just the first word of the string param.

This is an extract of code to simplify for you:

#!/bin/sh

test="Good morning"
printf "\n"
printf $test
printf "\n"

This code outputs just Good.

Jens
  • 69,818
  • 15
  • 125
  • 179

2 Answers2

5

Double-quote your variable to avoid getting Word-splitting by shell

printf "$test"

Moreover, the general syntax for printf like C would be to have

printf <FORMAT> <ARGUMENTS...>

The text format is given in <FORMAT>, while all arguments the format string may point to are given after that, here, indicated by <ARGUMENTS…>.

The problem you are seeing is because an unquoted variable in bash invokes the word-splitting. This means that the variable is split on whitespace (or whatever the special variable $IFS has been set to) and each resulting word is used as a glob (it will expand to match any matching file names). Your problem is with because of the splitting part.

Inian
  • 80,270
  • 14
  • 142
  • 161
2

Correct. Only the first argument is the format string, the others are additional arguments to be formatted. Just like in C.

printf '\n'
printf '%s' "$test"
printf '\n'
Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358