5

I have a file called "physics 1b.sh". In bash, if I try

x="physics 1b"
grep "string" "$x".sh

grep complains:

grep:  physics 1b: No such file or directory.

However, when I do

grep "string" physics\ 1b.sh 

It works fine. So I guess the problem is something to do with the variable not being expanded to include the backslash that grep needs to recognize the space. How do I get this to work?

Using bash 3.2, mac os 10.6.

Edit:
Never mind, the problem was that x was set to " physics 1b", but when I did echo $x to check the contents, bash chopped off the spaces in the front so I couldn't tell that it was different. The first way above actually works.

jww
  • 97,681
  • 90
  • 411
  • 885
nightfire
  • 815
  • 2
  • 12
  • 22
  • Note that there is a space in front of '` physics 1b`' in the error from grep; are you sure it didn't mention .sh on the end of the file name? – Jonathan Leffler Mar 30 '10 at 07:12

3 Answers3

9

Put the entire argument in double-quotes:

grep "string" "$x.sh"
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
2

use this in your script.

grep "string" "${x}.sh"
Vijay
  • 65,327
  • 90
  • 227
  • 319
0

another way

grep "string" "${x}.sh"
ghostdog74
  • 327,991
  • 56
  • 259
  • 343