Skip to main content
Formatting, minor rephrasing, typo
Source Link
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

In the Bash Pitfalls on "Greg's Wiki" I found the following quote:

In fact, the echoecho command cannot be used with absolute safety here. If the variable contains -n-n for example, echoecho will consider that an option, rather than data to be printed. The only absolutely sure way to print the value of a variable is using print: printf "%s\n" "$foo" source:

printf "%s\n" "$foo" 

WhenBut when I type:

var="-n Hello" echo "$var" 
var="-n Hello" echo "$var" 

It works properly and doesn't interpret -n-n as an option, so I don't understand why the source I quoted says that we need to use printfprintf to be absolutely safe?

In fact, the echo command cannot be used with absolute safety here. If the variable contains -n for example, echo will consider that an option, rather than data to be printed. The only absolutely sure way to print the value of a variable is using print: printf "%s\n" "$foo" source

When I type:

var="-n Hello" echo "$var" 

It works properly and doesn't interpret -n as an option, so I don't understand why the source I quoted says that we need to use printf to be absolutely safe?

In the Bash Pitfalls on "Greg's Wiki" I found the following quote:

In fact, the echo command cannot be used with absolute safety here. If the variable contains -n for example, echo will consider that an option, rather than data to be printed. The only absolutely sure way to print the value of a variable is using printf:

printf "%s\n" "$foo" 

But when I type:

var="-n Hello" echo "$var" 

It works properly and doesn't interpret -n as an option, so I don't understand why the source I quoted says that we need to use printf to be absolutely safe?

Post Closed as "Duplicate" by Stephen Kitt shell-script
Rephrase title, add relevant tags
Link
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

"If the variable contains Why is it recommended to use "printf -n for example, echo will consider that an option, rather than data to be printed.- <arguments>" instead of "echo <arguments>?"

Source Link

"If the variable contains -n for example, echo will consider that an option, rather than data to be printed."

In fact, the echo command cannot be used with absolute safety here. If the variable contains -n for example, echo will consider that an option, rather than data to be printed. The only absolutely sure way to print the value of a variable is using print: printf "%s\n" "$foo" source

When I type:

var="-n Hello" echo "$var" 

It works properly and doesn't interpret -n as an option, so I don't understand why the source I quoted says that we need to use printf to be absolutely safe?