Grep error due to variable expansion with spaces

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 

Works fine. So I think the problem is that the variable is not expanded to include the backslash needed by grep to recognize the space. How do I make this work?

Using Bash 3.2, Mac OS 10.6.

Edit:
It doesn't matter, the problem was that the value was set for x " physics 1b", but when I did echo $xto check the contents, bash trimmed the spaces in the front, so I could not say that it was different. The first method above actually works.

+4
3

:

grep "string" "$x.sh"
+8

script.

grep "string" "${x}.sh"
+2

another way

grep "string" "${x}.sh"
0
source

Source: https://habr.com/ru/post/1739099/


All Articles