0

Could you please explain the difference between:

echo ${hostname}; and echo $(hostname);

echo ${hostname}; - shows nothing, just an empty line. echo $(hostname); - shows information from /etc/hostname.

tested on Ubuntu 22.04.1 and CentOS 7

wa-ah
  • 3

1 Answers1

4

${hostname} or $hostname is called parameter expansion, and here it gives the value of the shell variable hostname. It's probably unset, so you get the empty string which gets removed during word splitting since the expansion is not quoted. But you could of course define it, and Bash would automatically fill the uppercase HOSTNAME with the hostname.

See e.g. $VAR vs ${VAR} and to quote or not to quote

$ hostname=foo
$ echo "$hostname"
foo

$(hostname) is called command substitution, and here it runs the command hostname and gives its output.

$ hostname
ulpukka
$ foo=$(hostname)
$ echo "$foo"
ulpukka

Word splitting applies to both unquoted parameter expansions and command substitutions, see e.g. Quoting within $(command substitution) in Bash and When is double-quoting necessary?

ilkkachu
  • 138,973