0

Hello "${world}" "Hello ${world}" in bash script should behave the same, but which one of them is a better practise?

Something like "${base_dir}"/"${filename}" looks ugly, right?

Toto
  • 89,455
  • 62
  • 89
  • 125
lifang
  • 1,485
  • 3
  • 16
  • 23
  • `looks ugly, right?` Looks fine for me. – KamilCuk May 07 '21 at 08:35
  • In the general case, depends on what you mean. `echo` specifically is not a particularly good example because it often doesn't matter if your arguments are separate strings; for many other commands, it's a lot more crucial. If you don't know exactly what you mean, usually quoting everything is the better approach. See also [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee May 07 '21 at 08:58

1 Answers1

4

The command echo Hello "${world}" takes two arguments: "Hello" and whatever string the variable world is set to. It outputs them with a single space between them.

You have more control over the output by giving echo a single string argument. For example, if you want a tab instead of a space, you can enter a tab character between the words of the passed string: echo "Hello<tab>${world}" whereas you'd get a space if you give them as separate arguments.

The command echo "${base_dir}"/"${filename}" takes a single argument, because there are no space separators. There is no reason not to use echo "${base_dir}/${filename}".

k314159
  • 5,051
  • 10
  • 32