0

The current directory contains file1 and file2. How do you explain this output:

[root@server test]# command='*';
[root@server test]# echo $command
file1 file2

Why is * expanded? I expect it not to be because it's quoted.

jaudo
  • 103
  • 3
  • 1
    Because `$command` is unquoted. Try `"$command"`, and you'll get `*`. – Benjamin W. Nov 15 '18 at 15:08
  • Right... but I don't really understand why it has to be quoted... – jaudo Nov 15 '18 at 15:10
  • Actually I think Stephane's question is a more appropriate duplicate: https://unix.stackexchange.com/q/171346/237982 – jesse_b Nov 15 '18 at 15:12
  • When the command is interpreted, it undergoes a few [expansions](https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions). Relevant in this case: parameter expansion (turns `$command` into `*`), and then filename expansion (turns `*` into filenames in the current directory). Quoting suppresses that second expansion. – Benjamin W. Nov 15 '18 at 15:13

1 Answers1

1

command='*' does indeed as you expect set the value of $command to a literal *. However, when you run echo $command, the value of $command is expanded to *, making your command echo *. The wildcard is then expanded as per usual. To prevent this, quote the parameter you are giving to echo:

$ v='*'
$ echo "$v"
*
DopeGhoti
  • 73,792
  • 8
  • 97
  • 133