0

I want to store the contents of a file in a bash shell variable. This works fine:

$ cat hello
Hello, world!
$ F=hello
$ Q=$(cat $F)
$ echo $Q
Hello, world!

However, if the file contains an asterisk, the asterisk is replaced by a list of all files in the current directory.

How can I quote the filename to protect the asterisk? Or otherwise load the file into the shell variable?

I am aware of this question, but it doesn't work for files that contain an asterisk.

Cyrus
  • 77,979
  • 13
  • 71
  • 125
user448810
  • 16,961
  • 2
  • 32
  • 56

1 Answers1

4

Q contains the asterisk. It is the unquoted expansion of $Q that replaces the * with a list of files.

$ Q="*"
$ echo $Q
<list of files>
$ echo "$Q"
*

The right-hand side of an assignment is not subject to path name expansion, so Q=* would work as well, and the command substitution used to read from the file is also not affected. Q=$(cat hello) works fine: you just need to quote the expansion of Q.

chepner
  • 446,329
  • 63
  • 468
  • 610