0

Can someone please explain to me why these 3 commands produce different outputs?

printf "%s"  `echo ../.. | sed 's/[.]/\\&/g'`
printf "%s" $(echo ../.. | sed 's/[.]/\\&/g')
printf "%s" "$(echo ../.. | sed 's/[.]/\\&/g')"
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Teodor
  • 1
  • 1
    They don't. For me, all of them write `&&/&&` (after adding the missing backtick on the first.). Which command gives you something different? I guess you are seeing `../..` for one of them. – William Pursell Mar 12 '22 at 16:12
  • They all produce the same output. – Talel BELHADJSALEM Mar 12 '22 at 16:13
  • 1
    The results are really different - https://ideone.com/8d4aQg – Wiktor Stribiżew Mar 12 '22 at 16:35
  • Backticks are expected to change how backslashes (and other backticks) behave within them. It's documented and normal, and is part of why `$( )` is preferred instead. – Charles Duffy Mar 12 '22 at 16:40
  • As always, you should use `set -x` to enable tracing when trying to figure out how your code is interpreted by a shell. See https://ideone.com/VLLNql showing Wiktor's link with that tracing active. – Charles Duffy Mar 12 '22 at 16:41
  • 1
    @TalelBELHADJSALEM, if backticks didn't change how backslashes behave within them, they wouldn't be nestable (that is to say, if these three lines all had the same output, there would be no backtick-based equivalent to `echo $(echo hello $(echo world) )` possible). – Charles Duffy Mar 12 '22 at 16:45
  • ...see also [BashFAQ #82](https://mywiki.wooledge.org/BashFAQ/082) and the links therein (including to [section 2.6.3 of the POSIX sh specification](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_03)). – Charles Duffy Mar 12 '22 at 16:48
  • consider updating the question with the output generated by your code; I get the same output as per Wiktor's link – markp-fuso Mar 12 '22 at 16:56
  • this is the ouput: ++ echo ../.. ++ sed 's/[.]/\&/g' + printf %s '&&/&&' ++ echo ../.. ++ sed 's/[.]/\\&/g' + printf %s ../.. ++ echo ../.. ++ sed 's/[.]/\\&/g' + printf %s '\.\./\.\.' – Teodor Mar 12 '22 at 17:37

0 Answers0