Grep error due to expanding variables with spaces

妖精的绣舞 提交于 2019-12-20 01:36:08

问题


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.


回答1:


Put the entire argument in double-quotes:

grep "string" "$x.sh"



回答2:


use this in your script.

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



回答3:


another way

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


来源:https://stackoverflow.com/questions/2543309/grep-error-due-to-expanding-variables-with-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!