2

I have a shell script that prints the first argument passed to it in the command line. I was experimenting with $1 and "$1". Interestingly to me, when I pass "John Doe" I get different outputs.

hw Version1

#!/bin/bash
printf "Hello %s\n" $1

Result is the following. Seems like it loops through strings separated by space:

$ hw "John Doe"
Hello John
Hello Doe

hw Version2

#!/bin/bash
printf "Hello %s\n" "$1"

Result is:

$ hw "John Doe"
Hello John Doe

what is the difference between $1 and "$1" when the argument in the command line is something like "string1 string2 ... stringn"?

afp_2008
  • 497
  • 1
  • 3
  • 11
  • 1
    Related: [When is double-quoting necessary?](https://unix.stackexchange.com/questions/68694/when-is-double-quoting-necessary) – steeldriver Aug 21 '20 at 23:15
  • 1
    It's a duplicate all right but the question is well framed and formatted. IMO doesn't deserve a downvote – iruvar Aug 21 '20 at 23:24
  • Thank you. I was surprised when it was downvoted. – afp_2008 Aug 22 '20 at 00:38
  • 1
    What is not covered elsewhere is why Hello appears twice in Version 1. This is a specific action by the printf built-in: "The format is reused as necessary to consume all of the arguments." – Paul_Pedant Aug 22 '20 at 10:39

0 Answers0