cat command with a variable that has spaces

1

I need to use cat command to display the contents of a file, and the filename has spaces in them: "embedded board link.rtf".

I assign the filename using a variable: I="embedded board link.rtf", but when I use cat $I, I have this error message.

wireless-10-146-35-118 Desktop> cat $I
cat: embedded: No such file or directory
cat: board: No such file or directory
cat: link.rtf: No such file or directory

What might be wrong?

prosseek

Posted 2017-06-03T18:14:34.443

Reputation: 4 635

Answers

6

You have to quote the variable too:

I="embedded board link.rtf"
cat "$I"

This is because the shell will first expand any variables, and then parse the command:

  1. cat $1
  2. cat embedded board link.rtf

When you really meant the following:

  1. cat "$1"
  2. cat "embedded board link.rtf"

Note that in bash and many other shells, variables inside single quotes will not be expanded:

  1. cat '$1'
  2. cat '$1'

Attie

Posted 2017-06-03T18:14:34.443

Reputation: 14 841