开发者

Grep error due to expanding variables with spaces

开发者 https://www.devze.com 2022-12-24 21:27 出处:网络
I have a file called \"physics 1b.sh\". In bash, if I try x=\"physics 1b\" grep \"string\" \"$x\".sh grep complains:

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.

Ho开发者_如何学Gowever, 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.


Put the entire argument in double-quotes:

grep "string" "$x.sh"


use this in your script.

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


another way

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号